find
is not correct. If the final character occurs elsewhere in the string, the method returnsTrue
at that point. You can fix this and simplify the code at the same time:@staticmethod def find(trie, word): for char in word: if char in trie.child: trie = trie.child[char] else: return False return True
The point of static methods is that they can be called without an instance of the class. Your static methods expect an instance as the first argument. Thus they could be normal instance methods instead.
Here the first assignment is redundant. If
dict
lookup raisesKeyError
, that will occur before the assignment anyway, so the value ofnode
is preserved even if you only usenode = node.child[s[i]]
.try: _ = node.child[s[i]] node = node.child[s[i]] i = i + 1 except KeyError: break
The
while
loops can be changed tofor
loops like this for example:def insert(self, s, value = 0): node = self for i, char in enumerate(s): try: node = node.child[char] except KeyError: break else: i += 1 # (* append new nodes, if necessary *) for char in s[i:]: node.child[char] = node = Trie() node.value = value
(Note that in a chained assignment like
node.child[char] = node = Trie()
the right-hand-side is evaluated first and then assigned to the targets from left to right)You could also take advantage of
collections.defaultdict
and greatly simplifyinsert
:def __init__(self): self.child = collections.defaultdict(Trie) def insert(self, s, value = 0): node = self for char in s: node = node.child[char] node.value = value