-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdictrie.py
66 lines (57 loc) · 1.99 KB
/
dictrie.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
try:
from UserDict import UserDict
except ImportError:
from collections import UserDict
from collections import deque
class Dictrie(UserDict, object):
def __init__(self, *wordslists, **kwargs):
init_trie = kwargs.get('dict', {})
super(Dictrie, self).__init__(init_trie)
for words in wordslists:
self.build_trie(words)
# returns if word is a valid word in the dictionary
def is_word(self, word):
return word in self and ' ' in self[word]
# returns a generator to produce all words in the trie beginning with
# the root from shortest to longest
def get_words(self, root):
queue = deque([root])
while queue:
curr_str = queue.popleft()
if not self[curr_str]:
yield curr_str.strip()
else:
queue.extend(curr_str + key for key in sorted(self[curr_str].iterkeys()))
# builds the trie given an iterator of words
def build_trie(self, words):
words = list(words)
for word in words:
self[' '] = word
def __iter__(self):
queue = deque(sorted(self.iterkeys()))
while queue:
curr_str = queue.popleft()
if not self[curr_str]:
yield curr_str.strip()
else:
queue.extend(curr_str + key for key in sorted(self[curr_str].iterkeys()))
def __contains__(self, key):
sub_trie = self.data
for char in key:
if char in sub_trie:
sub_trie = sub_trie[char]
else:
return False
return True
def __getitem__(self, key):
sub_trie = self.data
for char in key:
if char in sub_trie:
sub_trie = sub_trie[char]
else:
raise KeyError(key)
return sub_trie
def __setitem__(self, key, item):
sub_trie = self.data
for char in item.strip() + ' ':
sub_trie = sub_trie.setdefault(char, {})