如何存储self.astring而不是每次递归时都清除数据?

时间:2017-06-11 06:38:26

标签: python recursion tree

我有一个列表样式的树代码(例如'[o [p [q] [r]] [s]]')我想得到树的叶子。 我使用我的教科书中的代码并尝试获取叶子,但是代码(即'def print_tree_with_prefix')是递归的,因此每次运行该方法时,它都会删除我想要的数据。任何人都可以提出任何想法吗?

以下是代码:

class Tree:

    def __init__(self, new_key):
        self.key = new_key
        # represent children of a node with a list
        self.children = []  
        # number of nodes in the subtree rooted at this node
        self.num_of_descendants = 0    

    # prints the tree using the specified prefix for the current line
    def print_tree_with_prefix(self, line_prefix, last_child):
        self.astring = ''#it just erases the data as the method is recursive
        count = 0

        # generate the prefix for the next line
        if len(self.children) > 0:
            next_prefix = line_prefix
            for child_index in range(len(self.children)-1):
                 self.children[child_index].print_tree_with_prefix(next_prefix, False)
            self.children[-1].print_tree_with_prefix(next_prefix, True)

        else:
            self.newkey = self.key
            self.astring = self.astring + self.key #add a new data in the string
            print(self.astring)

def load_tree(tree_str, pos = 0):
    new_node = None
    while pos < len(tree_str):
        if tree_str[pos] == "[":
            pos += 1
            new_node = Tree(tree_str[pos])
            while pos < len(tree_str) and tree_str[pos + 1] != "]":
                pos += 1
                child_tree, pos = load_tree(tree_str, pos)
                if child_tree:
                    new_node.children.append(child_tree)
                    new_node.num_of_descendants += \
                        1 + child_tree.num_of_descendants
            return new_node, pos + 1
        else:
            pos += 1
    return new_node, pos

def main():
    tree, processed_chars = load_tree('[o[p[q][r]][s]]') #the sample tree
    tree.print_tree_with_prefix("", True)

main()

输出是: q [R 小号 (在单独的行中)

预期产量: 夸特 (整个连接字符串)

所以'def print_tree_with_prefix'的'else'部分效果不好......任何人都可以帮忙吗? :(

1 个答案:

答案 0 :(得分:0)

听起来你正在尝试使用输出的串联返回单个字符串,而不是将它打印出来,直到现在为止?

如果是这样,那么修改你的算法就可以很容易了,但是这可以归结为一个更简单的代码片段(剥离出几个未使用的变量):

def print_tree_with_prefix(self):
    if not self.children:
        return self.key
    return ''.join([child.print_tree_with_prefix() for child in self.children])

用以下方式调用它:

def main():
    tree, processed_chars = load_tree('[o[p[q][r]][s]]')
    print tree.print_tree_with_prefix()

产地:

qrs

为了帮助您了解或许值得研究如何以最小的更改修复原始算法。

我认为您所犯的关键错误是认为每个递归调用都会附加一个astring变量。

事实上,有一个单独的&#39; astring&#39;变量per Tree实例和`print_tree_with_prefix&#39;不返回值。要解决此问题,我们只需更改代码即可将数据返回到父调用:

# prints the tree using the specified prefix for the current line
def print_tree_with_prefix(self, line_prefix, last_child):
    astring = ''#it just erases the data as the method is recursive
    count = 0

    # generate the prefix for the next line
    if len(self.children) > 0:
        next_prefix = line_prefix
        for child_index in range(len(self.children)-1):
             astring += self.children[child_index].print_tree_with_prefix(next_prefix, False)
        astring += self.children[-1].print_tree_with_prefix(next_prefix, True)
        return astring
    else:
        self.newkey = self.key
        astring = astring + self.key #add a new data in the string
        return astring

最后打印出来:

def main():
    tree, processed_chars = load_tree('[o[p[q][r]][s]]') #the sample tree
    print tree.print_tree_with_prefix("", True)

之后,只是简化代码并删除已使用的变量。