简体   繁体   中英

building a tree in python

im trying to build a tree according to a given list of elements where every element makes a whole level. element0 is the root then element1 is the first level and so on.

this is my code:

example: for a given list ["fever", "headache", "fatigue"] my tree would be:
                    fever
    #          Yes /       \ No
    #        headache           headache
    #   Yes /     \ No     Yes/     \No
    #     fatigue   fatigue  fatigue fatigue 
class Node:
    def __init__(self, data, positive_child = None, negative_child = None):
        self.data = data
        self.positive_child = positive_child
        self.negative_child = negative_child
    def __str__(self):
        return str(self.data)

def tree_helper(symptoms,tree_nodes):
    if len(symptoms) == 0:
        return
    if len(symptoms) == 1:
        symptoms[0] = Node(symptoms[0])
        tree_nodes.append(symptoms[0])
        print('OK')
    else:
        yes_root = Node(symptoms[0],symptoms[1],symptoms[1])

        tree_nodes.append((yes_root))
        tree_helper(symptoms[1:],tree_nodes)
        no_root = Node(symptoms[0],symptoms[1],symptoms[1])
        tree_nodes.append(no_root)
        tree_helper(symptoms[1:],tree_nodes)
        return tree_nodes

def build_tree(symptoms):
    tree_nodes = []
    if len(symptoms) > 1:
        tree_nodes = tree_helper(symptoms,tree_nodes)
    for i in tree_nodes:
        print(i.data, i.positive_child,i.negative_child)

if __name__ == "__main__":
    build_tree(["fever","headache","fatigue"])

it seems to be making nodes of only the left most path and right most path and its adding them twice.

You can build the nodes and then add connections.

# each layer has 2^i nodes for i = 0,1,2..
nodes = [[Node(s) for _ in range(pow(2,i))] for i,s in enumerate(s)]

# add connections
for i in range(len(nodes)-1):
    for parent in nodes[i]:
        parent.positive_child = nodes[i+1][2*i]
        parent.negative_child = nodes[i+1][2*i + 1]


tree = nodes[0][0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM