import typing
from typing import Optional, Dict
from collections.abc import Iterator
class TrieNode:
def __init__(self):
self.children: Dict[str, TrieNode] = {} # maps a child letter to its TrieNode class
self.is_word = False # whether or not this Node is a valid word ending
self.counter = 0 # a counter indicating how many times a word is inserted
class TrieDictionary():
def __init__(self):
self.root: TrieNode = TrieNode()
def load_dictionary(self, filename: str) -> None:
# add every word to the trie, not just the words over some length.
node = self.root
with open(filename) as wordsfile:
for line in wordsfile:
word = line.strip().lower() # Do something with word here
for letter in word:
if letter not in node.children:
node.children[letter] = TrieNode()
node = node.children[letter]
node.is_word = True
node.counter += 1
def contains(self, word: str) -> bool:
node = self.root
for letter in word:
if letter not in node.children:
return False
node = node.children[letter]
return node.is_word
# Define the file path for the dictionary file
WORDS_FILE = "words.txt"
# Read all words from the file and store them in a list
with open(WORDS_FILE) as file:
words = [line.strip() for line in file]
# Test the contains() method for all words in the dictionary file
def test_contains_all_example():
# Make dictionary
game_dict = TrieDictionary()
game_dict.load_dictionary(WORDS_FILE)
# Check that the contains() method returns True for all the words
for s in words:
assert game_dict.contains(s)
# Run the test
test_contains_all_example()
У меня есть образец файла, который содержит слова {aa,aah,aahed,aahing,aahs,aal,aalii,aaliis,aals}. Проблема в том, что при запуске теста я получаю ошибку утверждения. Я попытался отладить, чтобы выяснить, что не так. Я узнал, что все результаты были ложными. при отладке метода load_dictionary я вижу, что он создает дочерний элемент для каждой буквы при чтении слов, при этом я считаю, что он не должен их дублировать, если они существуют. Например, если «аа» уже есть, следует добавить только «h», чтобы добавить слово «аа». В настоящее время после первого «аа» будет «аа». Вот что я предполагаю, я действительно не уверен, какой метод вызывает проблему! Я ценю вашу помощь в выяснении этого.
Этот код не определяет BoggleDictionary. Пожалуйста, опубликуйте полный код.
Извините за путаницу, я отредактировал вопрос. Надеюсь, поможет.






Ваш метод load_dictionary инициализируется node не в том месте. Вам необходимо повторно инициализировать его каждый раз, когда вы хотите добавить новое слово, но ваш текущий код делает это только один раз. В вашем Trie каждое слово после первого добавляется к концу предыдущего слова.
Чтобы устранить проблему, переместите строку node = self.root внутрь цикла:
def load_dictionary(self, filename: str) -> None:
with open(filename) as wordsfile:
for line in wordsfile:
word = line.strip().lower()
node = self.root # move this line here!!!!
for letter in word:
if letter not in node.children:
node.children[letter] = TrieNode()
node = node.children[letter]
node.is_word = True
node.counter += 1
Посетите раздел Как спрашивать, чтобы получить советы, например, как написать хороший заголовок.