我正在嘗試創建一個trie單詞串列["Patrick",'Pete','Peter']。
為什么下面的代碼return {}?以及如何在構建后列印 trie 本身?
def trieSetUpForWords(words):
trie = {}
for word in range(len(words)):
currentWord = words[word]
for char in range(len(currentWord)):
currentLetter = currentWord[char]
if currentLetter not in trie:
trie[currentLetter] = {}
trie = trie[currentLetter]
return trie
print(trieSetUpForWords(["Patrick",'Pete','Peter']))
uj5u.com熱心網友回復:
為了回傳trie,您可能希望將其存盤在root安全的地方并回傳:
def trie_setup_for_words(words):
root = {}
trie = root
for current_word in words:
for current_letter in current_word:
if current_letter not in trie:
trie[current_letter] = {}
trie = trie[current_letter]
# Mark the end of a word
trie['*'] = '*'
# The root is also needed to reset it when a new word is added
trie = root
# Return the root here, not just the last leaf
return root
if __name__ == "__main__":
trie = trie_setup_for_words(["Patrick", 'Pete', 'Peter'])
如果我們列印出trie,我們將看到如下內容:
{'P': {'a': {'t': {'r': {'i': {'c': {'k': {'*': '*'}}}}}}, 'e': {'t': {'e': {'*': '*', 'r': {'*': '*'}}}}}}
為了確保正確構造出 trie,我們可能想要測驗一個詞是否存在于trie:
def contains_word(trie: dict, word: str):
if not word and '*' in trie:
return True
if word and word[0] in trie:
return contains_word(trie[word[0]], word[1:])
return False
這將回傳以下結果:
print(contains_word(trie, "Patrick")) # Prints True
print(contains_word(trie, "Patric")) # Prints False
print(contains_word(trie, "Pete")) # Prints True
print(contains_word(trie, "Peter")) # Prints True
print(contains_word(trie, "Pet")) # Prints False
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/401160.html
上一篇:收集串列中所有具有相同專案數的串列,并用它創建一個字典
下一篇:為什么我的Python程式的可執行版本沒有正確執行os.listdir和os.path.isdir?作業系統是Windows10
