【发布时间】:2018-05-01 07:57:15
【问题描述】:
我编写了一个实现 Trie 数据结构的代码,它接收字符串列表和字符串的计数。
lst = [['james',9],['chloe',20],['chlara',30]]
字符串是名称,后面的整数值是计数。一旦构建了 trie,它就会提示用户输入前缀,
userinput = ch
这样,代码将返回字符串 chlara,因为它与具有前缀 ch 的 chloe 相比具有更高的计数。我已经成功构建了 Trie,但我在搜索功能方面遇到了困难。
class Node:
def __init__(self):
self.children = [None] * 26
self.end = False
self.frequency = 0
self.goindex = 0
self.index = 0
class Trie:
def __init__(self):
self.root = Node()
def ord_char(self,key):
ord_rep = ord(key) - ord('a')
return ord_rep
def add_word(self,lst):
word = lst[0] #word
freq = lst[1] #frequency of string
word_len = len(word)
current = self.root #start from root node
for i in range(word_len):
position = self.ord_char(word[i])
if current.children[position] is None:
current.children[position] = Node()
current = current.children[position]
if current.frequency > freq:
continue
else:
current.frequency = freq
current.index = position
current.end = True #end of string
def main():
trie = Trie()
for i in list2:
trie.add_word(i)
user = input("Enter a prefix: ")
print(trie.prefix_search(user))
if __name__ == "__main__":
main()
我收到了不完整的字符串“chla”,我很确定这是因为我的搜索功能效率低下且无法正常工作。
更新
我现在面临的问题是,如果我的前缀是“aberr”,我将返回“aberration”而不是“aberr”
【问题讨论】: