Less busted trie

This commit is contained in:
Dan Buch 2023-10-26 20:44:05 -04:00
parent 88e4e319d3
commit 43a2e51712
Signed by: meatballhat
GPG Key ID: A12F782281063434

View File

@ -473,6 +473,8 @@ class Trie:
cur_t.kids.setdefault(prefix, next_val) cur_t.kids.setdefault(prefix, next_val)
cur_t = cur_t.kids[prefix] cur_t = cur_t.kids[prefix]
cur_t.kids["__leaf__"] = TrieNode("__leaf__", {})
def search(self, word: str) -> bool: def search(self, word: str) -> bool:
return self._has(word, prefix_ok=False) return self._has(word, prefix_ok=False)
@ -484,12 +486,14 @@ class Trie:
cur_t = self._t cur_t = self._t
value = cur_t.value value = cur_t.value
is_leaf: bool = False
while reverse_path and cur_t is not None: while reverse_path and cur_t is not None:
value = cur_t.value value = cur_t.value
is_leaf = "__leaf__" in cur_t.kids
cur_t = cur_t.kids.get(reverse_path.pop()) cur_t = cur_t.kids.get(reverse_path.pop())
if prefix_ok and cur_t is not None and value == word: if prefix_ok and cur_t is not None and value == word:
return True return True
return cur_t is None and value == word return (cur_t is None or is_leaf) and value == word