Skip to content

Instantly share code, notes, and snippets.

@thatguyintech
Last active October 4, 2017 23:15
Show Gist options
  • Save thatguyintech/4987417432af689f030517fff5bc14f6 to your computer and use it in GitHub Desktop.
Save thatguyintech/4987417432af689f030517fff5bc14f6 to your computer and use it in GitHub Desktop.
# add a word to an existing trie, recursively
def addWord(word, trie):
# non-base case
if word:
letter, rest = word[0], word[1:]
if letter not in trie:
trie[letter] = {}
addWord(rest, trie[letter])
# base case
else:
trie['$'] = None
trie = {}
addWord("apple", trie)
addWord("app", trie)
addWord("appo", trie)
addWord("api", trie)
trie == {'a': {'p': {'i': {'$': None}, 'p': {'l': {'e': {'$': None}}, 'o': {'$': None}, '$': None}}}} # True
@unzunz
Copy link

unzunz commented Oct 4, 2017

lgtm!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment