【问题标题】:Find Compound Words in List of Words using Trie使用 Trie 在单词列表中查找复合词
【发布时间】:2016-11-06 04:02:10
【问题描述】:

给定一个单词列表,我试图弄清楚如何在该列表中找到由列表中其他单词组成的单词。例如,如果列表是["race", "racecar", "car"],我想返回["racecar"]

这是我的一般思考过程。我知道使用 trie 对这类问题有好处。对于每个单词,我可以使用 trie 找到它的所有前缀(也是列表中的单词)。然后对于每个前缀,我可以检查单词的后缀是否由 trie 中的一个或多个单词组成。但是,我很难实现这一点。我已经能够实现 trie 和函数来获取单词的所有前缀。我只是坚持实现复合词检测。

【问题讨论】:

  • I have been able to implement the trie and and the function to get all prefixes of a word 发布您迄今为止尝试过的内容。然后人们可以在您的代码之上编写代码。

标签: python algorithm trie


【解决方案1】:

如果前缀是单词,您可以将 Trie 节点显示为 defaultdict 对象,这些对象已扩展为包含布尔标志标记。然后您可以进行两次处理,在第一轮将所有单词添加到 Trie 并在第二轮检查每个单词是否是组合:

from collections import defaultdict

class Node(defaultdict):
    def __init__(self):
        super().__init__(Node)
        self.terminal = False

class Trie():
    def __init__(self, it):
        self.root = Node()
        for word in it:
            self.add_word(word)

    def __contains__(self, word):
        node = self.root
        for c in word:
            node = node.get(c)
            if node is None:
                return False

        return node.terminal

    def add_word(self, word):
        node = self.root
        for c in word:
            node = node[c]

        node.terminal = True

    def is_combination(self, word):
        node = self.root
        for i, c in enumerate(word):
            node = node.get(c)
            if not node:
                break
            # If prefix is a word check if suffix can be found
            if node.terminal and word[i+1:] in self:
                return True

        return False

lst = ["race", "racecar", "car"]
t = Trie(lst)

print([w for w in lst if t.is_combination(w)])

输出:

['racecar']

【讨论】:

  • 啊,这就是我所缺少的。我想如果你稍微改变一下你的函数is_combination,它就会起作用。在您有条件地检查后缀时,我会将其更改为:if node.terminal and (word[i+1:] in self or self.is_combination(word[i+1:])) 您的代码只会查找由两个单词组成的复合词。但是,它们也可以由 3 个或更多单词组成。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 2021-06-03
  • 2012-12-14
  • 2012-08-09
  • 1970-01-01
相关资源
最近更新 更多