【发布时间】:2010-09-20 20:32:10
【问题描述】:
问题:
我有一个trie,我想返回其中存储的信息。有些叶子有信息(设置为值> 0),有些叶子没有。我只想返回那些有价值的叶子。
正如所有 trie 在每个节点上的叶子数都是可变的,每个值的键实际上是由到达每个叶子所需的路径组成的。
我正在尝试使用生成器来遍历树后序,但我无法让它工作。我做错了什么?
我的模块:
class Node():
'''Each leaf in the trie is a Node() class'''
def __init__(self):
self.children = {}
self.value = 0
class Trie():
'''The Trie() holds all nodes and can return a list of their values'''
def __init__(self):
self.root = Node()
def add(self, key, value):
'''Store a "value" in a position "key"'''
node = self.root
for digit in key:
number = digit
if number not in node.children:
node.children[number] = Node()
node = node.children[number]
node.value = value
def __iter__(self):
return self.postorder(self.root)
def postorder(self, node):
if node:
for child in node.children.values():
self.postorder(child)
# Do my printing / job related stuff here
if node.value > 0:
yield node.value
使用示例:
>>trie = Trie()
>>trie.add('foo', 3)
>>trie.add('foobar', 5)
>>trie.add('fobaz', 23)
>>for key in trie:
>>....print key
>>
3
5
23
我知道给出的示例很简单,可以使用任何其他数据结构来解决。然而,这个程序使用 trie 很重要,因为它对数据访问模式非常有益。
感谢您的帮助!
注意:我在代码块中省略了换行符,以便能够更轻松地复制粘贴。
【问题讨论】:
-
顺便说一句,你可以把叶子换成叶子
-
@Tim Mcnamara。唯一可见的生成器是生成器 function 而不是生成器 expression。
-
感谢@Aaron,我的错误。