Skip to main content
1 of 3
Janne Karila
  • 10.4k
  • 20
  • 34
  • find is not correct. If the final character occurs elsewhere in the string, the method returns True 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 raises KeyError, that will occur before the assignment anyway, so the value of node is preserved.

          try:
              _ = node.child[s[i]]
              node = node.child[s[i]]
              i = i + 1
          except KeyError:
              break
    
  • The while loops can be changed to for 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
    
Janne Karila
  • 10.4k
  • 20
  • 34