Skip to content

Instantly share code, notes, and snippets.

@daniel-abramov
Created June 12, 2016 16:24
Show Gist options
  • Save daniel-abramov/e42739b520608e0090bdb495d2443fa0 to your computer and use it in GitHub Desktop.
Save daniel-abramov/e42739b520608e0090bdb495d2443fa0 to your computer and use it in GitHub Desktop.
Simple implementation of trie data structure, O(n) for finding words
class Trie:
def __init__(self):
self.trie = dict()
def insert(self, key, value):
p = self.trie
for c in key:
if c not in p: p[c] = dict()
p = p[c]
p[None] = value
def find(self, key):
p = self.trie
for c in key:
if c not in p: raise KeyError
p = p[c]
if None not in p: raise KeyError
return p[None]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment