Steve Barnes
1 min readJan 23, 2018

--

Can I suggest adding at the top `from __future__ import print_function` then the code will also be python 2.7 compatible (and you could add the tag for that).

Personally I would also return node.word_finished from find_prefix — then you can tell if you have an acceptable whole word.

Most importantly you can simplify the check to just does a child node with the correct character exists (and get rid of the enumerate).

In [17]: def find_prefix(root, prefix: str) -> Tuple[bool, int]:
...: node = root
...: if not root.children:
...: return False, 0
...: for char in prefix:
...: char_not_found = True
...: for child in node.children:
...: if child.char == char:
...: char_not_found = False
...: node = child
...: break
...: if char_not_found:
...: return False, 0
...: return not char_not_found, node.counter
...:
In [18]: print(find_prefix(root, 'hammersd'))
(False, 0)
In [19]: print(find_prefix(root, 'hammers'))
(False, 0)
In [20]: print(find_prefix(root, 'hammer'))
(True, 1)

--

--

Steve Barnes
Steve Barnes

Written by Steve Barnes

0 Followers

Residing in Wales but living in my head. FOSS & Python fan & advocate.

Responses (1)