Python树:修改树

时间:2017-09-05 18:27:10

标签: python tree decision-tree binary-decision-diagram

这是我的python代码,用于制作有序二进制决策图(与上下文不太相关)。所以我只有一个特定高度的树,我需要将一些叶节点设置为一个。所以我有一个变量path,它包含一系列"决定",从该特定节点向左或向右移动。但是我的代码错误地修改了多个根。我对Python很新,当我使用C时,我常常依赖指针。

def makeCubes(arr):
        ans = []
        for ar in arr:
            ar2 = [ar[i:i + 2] for i in range(0, len(ar), 2)] 
            #splitting into segments of 2 each
            if not '00' in ar2:
                ans += [ar2]
        return ans

class Node:
    def __init__(self,key):
        self.key = key
        self.left = None
        self.right = None
    def addLeft(self,node):
        self.left = node
    def addRight(self,node):
        self.right = node

def makeTree(size):
    if(size == 1):
        leaf = Node('x0')
        leaf.addLeft(Node('zero'))
        leaf.addRight(Node('zero'))
        return leaf
    else:
        node = Node('x'+str(size-1))
        childNode = makeTree(size-1)
        node.addLeft(childNode)
        node.addRight(childNode)
        return node

def inOrder(root):
    if(root != None):
        return inOrder(root.left) + [root.key] + inOrder(root.right)
    return []

def makeOBDD(array):
    maxLen = max([len(word) for word in array])
    tree = makeTree(maxLen)
    for cube in array:
        tree = makeOne(tree,cube)
    return tree

def makeOne(root,cube):
    print("cube",cube)
    if(cube == []):
        print("updated")
        root.key = 'one'        
    else:
        element = cube[0]
        if(element == '01'):
            root.addLeft(makeOne(root.left,cube[1:]))
        elif(element == '10'):
            root.addRight(makeOne(root.right,cube[1:]))
    return root

# ab + a'b'
'''
Expected output
   x1
  /  \
 x0   x0
/ \   / \ 
1  0  0  1
'''
cubeSet = ['1010','0101']
cubes = makeCubes(cubeSet)
print(cubes)
obdd = makeOBDD(cubes)
print(inOrder(obdd))

0 个答案:

没有答案