Last active
August 29, 2015 13:56
-
-
Save vo/8994837 to your computer and use it in GitHub Desktop.
Rough outline of a Trie in Python, storing 10 digit numbers
This file contains 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
import random | |
class Trie: | |
def __init__(self): | |
self.children = [None]*10 | |
def insert(self, i, n): | |
if n == 1: | |
self.children[i] = True | |
else: | |
d = i / 10**(n-1) | |
r = i % 10**(n-1) | |
if not isinstance(self.children[d], Trie): | |
self.children[d] = Trie() | |
self.children[d].insert(r,n-1) | |
def search(self, needle, num_digits=10): | |
if num_digits == 1: | |
return (self.children[needle] == True) | |
else: | |
d = needle / 10**(num_digits-1) | |
if isinstance(self.children[d], Trie): | |
r = needle % 10**(num_digits-1) | |
return self.children[d].search(r, num_digits-1) | |
else: | |
return False | |
def list(self, prefix=0): | |
l = [] | |
for i in range(10): | |
c = self.children[i] | |
if c is not None: | |
if isinstance(c, Trie): | |
l.extend(c.list(prefix*10+i)) | |
else: | |
l.append(prefix*10+i) | |
return l | |
def __str__(self): | |
return str(self.list()) | |
# sample 1,000,000 random 10-digit numbers | |
nums = random.sample(xrange(10**10), 1000000) | |
# insert them into trie | |
trie = Trie() | |
for num in nums: | |
trie.insert(num, 10) | |
# test presence of a number | |
print len(trie.list()) | |
print trie.search(nums[444]) | |
print trie.search(9123456789) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment