【发布时间】:2017-03-01 19:17:46
【问题描述】:
def BFS(self, rootnode):
visited = []
queue = []
queue.append(rootnode)
while queue:
print(type(queue))
curr_node = (queue.pop())
for node in curr_node.nodes:
if node not in visited:
visited.append(node)
queue.append(node)
....
嗨,我正在尝试遍历这个 trie 对象,但我在遍历它的值时遇到了麻烦。数据结构包含节点,并且 每个节点包含两个值,一个字符值和一个其子节点的字典(保存在节点 = {} 中)。
我目前收到一个 AttributeError: str has no attribute nodes at the line "for node in curr_node.nodes:" 我似乎无法弄清楚为什么。我检查了返回类型节点的根节点的类型。我检查了返回类dict的队列节点对象的第一个值的类型。但是当我尝试遍历那个字典时 我得到属性错误。 *我也知道字典中的每个键都与一个节点配对。
我是否正确地遍历了 dicts?
*这里是初始调用 trie.BFS(trie.root.nodes['#'])
谢谢
【问题讨论】:
-
“我检查了队列的节点对象的第一个值的类型” - 你在说什么?你只打印了
type(queue)。 -
抱歉,省略了一行代码:我输入了返回类 dict 的 'print(type(queue[0].nodes))'
标签: python dictionary iteration breadth-first-search attributeerror