微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法编写一个函数来检索树中的所有单词

如何解决无法编写一个函数来检索树中的所有单词

我有以下 Trie 实现:

class TrieNode:
    def __init__(self):
        self.nodes = defaultdict(TrieNode)
        self.is_fullpath = False


class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self,word):
        curr = self.root
        for char in word:
            curr = curr.nodes[char]
        curr.is_fullpath = True

我正在尝试编写一种方法来检索我的尝试中所有单词的列表。

t = Trie()
t.insert('a')
t.insert('ab')
print(t.paths())  # ---> ['a','ab']

我目前的实现是这样的:

def paths(self,node=None):
    if node is None:
        node = self.root
    result = []
    for k,v in node.nodes.items():
        if not node.is_fullpath:
            for el in self.paths(v):
                result.append(str(k) + el)
        else:
            result.append('')
    return result

但它似乎没有返回完整的单词列表。

解决方法

以下是您代码中的问题:

  • is_fullpath 为 True 时,它​​看起来不会更远。但在这种情况下,您应该深入了解(对于更长的单词)。

  • 它不应该检查 node.is_fullpath 而是 v.is_fullpath

  • result.append('') 不正确。应该是 result.append(str(k))

因此您的 for 循环体可能如下所示:

if v.is_fullpath:
    result.append(str(k))
for el in self.paths(v):
    result.append(str(k) + el)

不过我会这样做:

在您的 TrieNode 类上定义此递归生成器方法:

def paths(self,prefix=""):
    if self.is_fullpath:
        yield prefix
    for chr,node in self.nodes.items():
        yield from node.paths(prefix + chr)

注意这如何将路径上收集的字符传递给递归调用。如果在任何时候 is_fullpath 布尔值为 True,我们就会生成该路径。我们总是通过子节点递归地继续搜索。

Trie 类上的方法非常简单:

def paths(self):
    return list(self.root.paths())

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。