Python 返回Trie中的字符串
我有这个问题:Python 返回Trie中的字符串,python,trie,Python,Trie,我有这个问题: a / \ b c / \ \ t y u 2 5 3 numbers at leaf stands for frequency, stored at the terminal node 我有默认的Trie搜索函数来搜索字符串。当我执行search('a')时,它将返回aby,因为它是插入频
a
/ \
b c
/ \ \
t y u
2 5 3
numbers at leaf stands for frequency, stored at the terminal node
我有默认的Trie搜索函数来搜索字符串。当我执行search('a')
时,它将返回aby
,因为它是插入频率最高的字符串。频率由我的函数中的self.count
存储。
我不想发布我的代码
您将如何解决从a
到y
的节点求解和返回问题?
提前感谢。您可以使用递归生成器函数遍历trie并生成包含搜索值作为子字符串的所有字符串: 简单的trie设置:
class Trie:
def __init__(self, l=None):
self.l, self.count, self.tree = l, 0, []
def insert_l(self, word):
if word:
if not (n:=[i for i in self.tree if i.l == word[0]]):
self.tree.append(Trie(word[0]))
self.tree[-1].add_word(word)
else:
n[-1].add_word(word)
def add_word(self, word):
if self.l is not None:
self.count += 1
self.insert_l(word if self.l is None else word[1:])
现在,可以将
搜索
方法添加到Trie
:
class Trie:
...
def search(self, word):
def _search(t, c = []):
if not t.tree:
yield c+[t]
else:
for i in t.tree:
yield from _search(i, c if t.l is None else c+[t])
if (l:=[(j, i) for i in _search(self) if word in (j:=''.join(k.l for k in i))]):
return max(l, key=lambda x:x[-1][-1].count)[0]
t = Trie()
words = ['abt', 'abt', 'aby', 'aby', 'aby', 'aby', 'aby', 'acu', 'acu', 'acu']
for word in words:
t.add_word(word)
print(t.search('a'))
输出:
'aby'
Id在every node ot trie中创建一个元素,该元素指示具有最大频率路径的子节点。然后基于此索引执行深度优先搜索。@AlbinPaul每个节点(字母)都由node.tree[index]表示,其中index是字母的ord。我应该如何基于此进行dfs?我不使用也不会使用任何字典/集合。那么,为每个节点找到一种机制,以指向它需要遍历的下一个节点。如果不看你写的代码,我就说不出多少。