简体   繁体   English

我的python树怎么了

[英]What's wrong with my python Tree

I'm trying to implement a tree structure, but when I'm trying to print data out in my tree, unexpected results are shown. 我正在尝试实现树结构,但是当我尝试在树中打印数据时,会显示意外的结果。

Correct result will be : 正确的结果将是:

root
 - A1
-- A2
--- A3
---- A4
----- A5

But I got : 但是我得到了:

root
 - A1
-- A1
--- A2
~ infinite loop

What's wrong with my code? 我的代码有什么问题? Can you answer me? 你可以回答我吗?

#!/usr/bin/python
class TreeNode :
    def __init__(self,key,obj=dict()) :
        print 'Node with '+key+' is created'
        self.key=key
        self.child=obj
    def add_child(self, key, obj) :
        self.child[key]=obj
        print 'child len ',
        print len(self.child)
    def get_child(self) :
        for key in self.child.keys() : 
            print key,
            pass
        print ''
        return self.child
    def find_child(self,key) :
        return self.child[key]
    def is_leap(self) : 
        print 'is_leap ',
        print len(self.child)
        if len(self.child)==0 :
            return 1
        else : return 0
    def append_rec(self,hier,data,depth) :
        # hier & data are lists
        if len(hier)== 1 : 
            print 'end of hierachy. append complete @ depth ',
            print depth
            return

        tmp = hier[0]
        tmp_child = hier[1:]
        name = str(hier[0])
        print 'self ',
        print tmp,
        print 'childs ',
        print tmp_child
        child_list = self.get_child()
        if child_list != None :
            if not name in child_list.keys() :  
                lc = TreeNode(name)
                self.add_child(name,lc)
                return lc.append_rec(hier[1:],data,depth+1)
            else :
                lc =child_list[name]
                return lc.append_rec(hier[1:],data,depth+1)
    def print_all(self,depth) :
        for i in range(depth) : print '-', 
        print self.key
        if len(self.child) == 0 : return
        if depth > 10 : 
            print 'depth limit over'
            return
        else :
            for k in self.child.keys() : 
                print 'Looking child having key = '+k
                return (self.child[k]).print_all(depth+1)




    # recursive method
class Tree :
    index = 0
    # root node of tree
    def __init__(self) :
        self.root=TreeNode('root')
        self.index=0
    def get_child(self) :
        return self.root.get_child()  
    def print_all(self) :
        self.root.print_all(0)
    def traverse(self) :
        node=self.root
        depth=0

        childs = node.get_child()
        if node.is_leap() : return
        else :
            for c in childs.keys() :
                print c,
                return self.traverse_rec(childs[c],depth+1)
        print ' end'

    def traverse_rec(self,node,depth) :
        i=0
        print 'depth ',
        print i,
        childs = node.get_child()
        if node.is_leap() : return
        else :
            for c in childs.keys() :
                print c,
                return self.traverse_rec(childs[c],depth+1)
        print ' end'


    def append(self,tup) :
        # root
        tmp = tup[0].split('/')
        data = tup[1]
        print 'root ['+data+']',
        tmp_child = tmp[1:]
        name = str(tmp[0])
        # if treenode with name tmp[0]
        child_list = self.root.get_child()
        if child_list != None :
            if not name in child_list.keys() :  
                #print 'name = '+name
                lc = TreeNode(name)
                self.root.add_child(name,lc)
                lc.append_rec(tmp_child,data,1)
            else :
                lc=child_list[name]
                lc.append_rec(tmp_child,data,1)


tree = Tree()
test_string = ('A1/A2/A3/A4/A5','example1')
tree.append(test_string)
tree.print_all()

In Python, default arguments are only evaluated once. 在Python中,默认参数仅计算一次。 So each time you create a TreeNode without an explicit obj argument, it gets assigned to the same dict. 因此,每次创建不带显式obj参数的TreeNode ,它将被分配给相同的字典。

One way to get around this is to use None as a default argument instead, like so. 解决此问题的一种方法是改为使用None作为默认参数。

def __init__(self,key,obj=None) :
    print 'Node with '+key+' is created'
    self.key=key
    self.child=obj if obj is not None else {}

Another option is to do a defensive copy. 另一种选择是进行防御性复制。 This will help in cases where you accidentally pass it a dict by reference when you don't want to, though this means that it may mask other bugs. 如果您不希望通过引用将其作为字典,这将很有帮助,尽管这意味着它可能掩盖了其他错误。 Also note that this will only do a shallow copy, which is usually what you want, but not always. 另请注意,这只会进行浅表复制,通常这是您想要的,但并非总是如此。

def __init__(self,key,obj=dict()) :
    print 'Node with '+key+' is created'
    self.key=key
    self.child=obj.copy()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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