【问题标题】:How to make depth search in Trie?如何在 Trie 中进行深度搜索?
【发布时间】:2020-03-27 13:16:09
【问题描述】:

我编写了我的 Trie 解决方案,其中我使用了 defaultdict。任务是找到所有带前缀的单词。 格式必须类似于 {of:[of, offten,进攻]}

这是我的 Trie 类:

from collections import defaultdict

def _trie():
    return defaultdict(_trie)

TERMINAL = None

class Trie(object):
    def __init__(self):
        self.trie = _trie()

    def addWord(self, word):
        trie = self.trie
        for letter in word:
            trie = trie[letter]
        trie[TERMINAL]


    def search(self, word, trie=None):
        if trie is None:
            trie = self.trie
        for i, letter in enumerate(word):
            if letter in trie:
                trie = trie[letter]
            else:
                return False
        return trie

这里是例子:

Trie = Trie()
Trie.addWord('of')
Trie.addWord('often')
Trie.addWord('offensive')


string = 'of'
s = dict(Trie.search(string))

他们给出结果:

【问题讨论】:

  • 写一个函数lookup(trie, prefix),它在一个单词的开头返回一个字典(dict)对“word:frequency”。例如,“of”键应返回 of,经常,攻击性等词。

标签: python algorithm nlp


【解决方案1】:

我在这里进行深度搜索

from collections import defaultdict
class TrieNode:
def __init__(self):
    self.child = defaultdict(TrieNode)
    self.is_word = False
    self.words = ""

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

def insert(self, word):
    cur = self.root
    for i in range(len(word)):
        cur = cur.child[word[i]]
        cur.words = word[:i+1]
    cur.is_word = True

def search(self, word):
    cur = self.root
    for char in word:
        cur = cur.child.get(char)
        if not cur:
            return []
    stack = [cur]
    res = []
    while stack:
        node = stack.pop()
        if node.is_word:
            res.append(node.words)
        for key, val in node.child.items():
            stack.append(val)
    return sorted(res)

Trie = Trie()
Trie.insert('of')
Trie.insert('often')
Trie.insert('offensive')
Trie.insert('offensive2')

Trie.search('o')

# ['of', 'offensive', 'offensive2', 'often']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    相关资源
    最近更新 更多