AnyTree Randomizer | Python

April 15th, 2021 12:11:39 AM

					
import anytree as at import random as rm # Generate a tree with node_count many nodes. Each has a number key that shows when it was made and a randomly selected color, red or white. def random_tree(node_count): # Generates the list of nodes nodes = [] for i in range(node_count): test = rm.randint(1,2) if test == 1: nodes.append(at.Node(str(i),color="white")) else: nodes.append(at.Node(str(i),color="red")) #Creates the various main branches for i in range(node_count): for j in range(i, len(nodes)): test = rm.randint(1,len(nodes)) if test == 1 and nodes[j].parent == None and (not nodes[i] == nodes[j]): nodes[j].parent = nodes[i] #Collects all the main branches into a single tree with the first node being the root for i in range(1, node_count): if nodes[i].parent == None and (not nodes[i] == nodes[0]): nodes[i].parent = nodes[0] return nodes[0]

Featured Posts