Skip to content

Instantly share code, notes, and snippets.

@nategraf
Created March 3, 2018 06:04
Show Gist options
  • Save nategraf/2949751543ab213dffecac531b44b55c to your computer and use it in GitHub Desktop.
Save nategraf/2949751543ab213dffecac531b44b55c to your computer and use it in GitHub Desktop.
Python Trie
class TrieNode:
def __init__(self, ch, final=False):
if ch:
ch = ch.lower()
self.ch = ch
self.final = final
self.children = {}
def addchild(self, child):
self.children[child.ch] = child
def next(self, ch):
return self.children.get(ch.lower(), None)
def buildtrie(strings):
return _buildtrie(TrieNode(None), (iter(s) for s in strings))
def _buildtrie(node, chiters):
map = {}
for chiter in chiters:
try:
ch = next(chiter)
if ch in map:
map[ch].append(ch)
else:
map[ch] = [chiter]
except StopIteration:
node.final = True
for ch, chiters in map.items():
node.addchild(_buildtrie(TrieNode(ch), chiters))
return node
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment