-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.py
More file actions
80 lines (63 loc) · 1.78 KB
/
trie.py
File metadata and controls
80 lines (63 loc) · 1.78 KB
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
80
"""
Implement Trie in Python.
References:
http://www.geeksforgeeks.org/trie-delete/
"""
def make_trie(*args):
"""
Make a trie by given words.
"""
trie = {}
for word in args:
if type(word) != str:
raise TypeError("Trie only works on str!")
temp_trie = trie
for letter in word:
temp_trie = temp_trie.setdefault(letter, {})
temp_trie = temp_trie.setdefault('_end_', '_end_')
return trie
def in_trie(trie, word):
"""
Detect if word in trie.
"""
if type(word) != str:
raise TypeError("Trie only works on str!")
temp_trie = trie
for letter in word:
if letter not in temp_trie:
return False
temp_trie = temp_trie[letter]
return True
def remove_from_trie(trie, word, depth):
"""
Remove certain word from trie.
"""
if word and word[depth] not in trie:
return False
if len(word) == depth + 1:
del trie[word[depth]]
if not trie: # Node becomes a leaf, indicate its parent to delete it.
return True
return False
else:
temp_trie = trie
# Recursively climb up to delete.
if remove_from_trie(temp_trie[word[depth]], word, depth + 1):
if temp_trie:
del temp_trie[word[depth]]
return not temp_trie
return False
if __name__ == '__main__':
trie = make_trie('hello', 'abc', 'baz', 'bar', 'barz')
print trie
print in_trie(trie, 'hello')
print in_trie(trie, 'bar')
print in_trie(trie, 'bab')
print in_trie(trie, 'zzz')
remove_from_trie(trie, 'abc', 0)
print trie
remove_from_trie(trie, 'hello', 0)
print trie
remove_from_trie(trie, 'bar', 0)
print trie
print in_trie(trie, 1)