-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.py
79 lines (54 loc) · 1.62 KB
/
trie.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
67
68
69
70
71
72
73
74
75
76
77
78
79
import pickle
import requests
pickle_path = "save.p"
class Node():
def __init__(self, char):
self.char = char
self.children = {}
self.is_terminus = False
def get_or_create_child(self, char):
if char in self.children:
return self.children[char]
node = Node(char)
self.children[char] = node
return node
def get_child(self, char):
return self.children.get(char)
def set_is_terminus(self):
self.is_terminus = True
class Trie():
def __init__(self):
self.parent = Node("")
def insert(self, word):
print("inserting", word)
node = self.parent
for char in word:
node = node.get_or_create_child(char)
node.set_is_terminus()
def get_prefix(self, word):
node = self.parent
for char in word:
node = node.get_child(char)
if not node:
return False
return node
def word_exists(self, word):
prefix_node = self.get_prefix(word)
return prefix_node and prefix_node.is_terminus
def seed_dictionary(self):
with open("/usr/share/dict/words") as f:
lines = f.readlines()
for line in lines:
self.insert(line.lower().strip())
def pickle(self):
self.__module__ = "trie"
pickle.dump(self, open(pickle_path, "wb"))
def get_trie(use_pickle=True):
try:
return pickle.load(open(pickle_path, "rb"))
except:
print("Trie cache not found, creating new Trie")
t = Trie()
t.seed_dictionary()
t.pickle()
return t