python - 从嵌套字典中检索分支

标签 python traversal trie

我有一个 python 嵌套字典(基本上是一个 trie 结构),以句子为分支 - 每个节点都是一个单词。像这样的东西: enter image description here

检索从根到提示(句子)的所有分支的最有效方法是什么?也就是说,我想要拥有所有可能的句子(我有一只狗,我有一把猎枪,我不喜欢猫王)。分支(句子)长度不是固定值。

最佳答案

您应该进行深度优先搜索并递归地生成句子的标记。 例如,使用生成器:

def yield_sentences(node):
    if node.is_leaf():
        yield node.word
    else:
        for child in node.children:
            for sentence in yield_sentences(child):
                yield '{} {}'.format(node.word, sentence)

用法:

>>> class Node(object):
...     def __init__(self, word, *children):
...             self.word = word
...             self.children = children
...     def is_leaf(self):
...             return not self.children
... 
>>> tree = Node('I', Node('have', Node('a', Node('dog'), Node('shotgun'))), Node("don't", Node('like', Node('Elvis'))))
>>> #tree is now your example tree
>>> list(yield_sentences(tree))
['I have a dog', 'I have a shotgun', "I don't like Elvis"]

关于python - 从嵌套字典中检索分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17080894/

相关文章:

python - 如何在 Python 中循环 HDF5 组,根据掩码删除行?

python - os.walk() 是否缺少指向目录的符号链接(symbolic link)?

C编程trie树插入

python 日期时间查询

python - 添加 "+"和 "-"的最佳方法?

python - __init__.storing 是什么信息?

python - 跟踪周期,同时向稀疏图中添加随机边

python - 基于 Python 中的几个正则表达式规则进行替换

这个递归函数可以在没有 `trav` 指针的情况下工作吗

c - 无法修复的内存泄漏