Created
March 3, 2018 06:04
-
-
Save nategraf/2949751543ab213dffecac531b44b55c to your computer and use it in GitHub Desktop.
Python Trie
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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