-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.py
26 lines (26 loc) · 993 Bytes
/
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
# This is an unconventional trie, in that its nodes are per-word. There's a hash table at each node to hold those lower nodes.
class Trie():
def __init__(self, parent=None, phrase=None, **kwargs):
self.hash = {}
self.phrase = phrase
self.parent = parent
return super().__init__(**kwargs)
def setPhrase(self, phrase):
self.phrase = phrase
def add(self, after, phrase=None):
if not phrase:
phrase = after
partition = after.split(' ',1)
if len(partition)>1:
if partition[0] in self.hash:
trie = self.hash[partition[0]]
else:
trie = Trie(self)
self.hash[partition[0]] = trie
trie.add(partition[1],phrase)
else:
if partition[0] in self.hash:
self.hash[partition[0]].setPhrase(phrase)
else:
trie = Trie(self, phrase)
self.hash[partition[0]] = trie