-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.py
More file actions
77 lines (52 loc) · 1.67 KB
/
trie.py
File metadata and controls
77 lines (52 loc) · 1.67 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
#!/usr/bin/env python
class Node:
def __init__(self, char, word):
self.char = char
self.word = word
self.children = {}
self.is_word = False
def sub_word(self):
if self.is_word:
return self.word
else:
return self.children.itervalues()[0].sub_word()
class Trie:
def __init__(self):
self.root = Node('', '')
def __getitem__(self, word):
def helper(word, cur_node):
children = cur_node.children
first_ch = word[0] if word else ''
if not len(word) or first_ch not in children:
return cur_node.sub_word()
else:
return helper(word[1:], children[first_ch])
return helper(word, self.root)
def __contains__(self, word):
cur_node = self.root
for char in word:
children = cur_node.children
if char not in children:
return False
cur_node = children[char]
return cur_node.is_word
def __str__(self):
pass
def add(self, word):
cur_node = self.root
for char in word:
children = cur_node.children
if char not in children:
new_word = cur_node.word + char
children[char] = Node(char, new_word)
cur_node = children[char]
cur_node.is_word = True
def has_prefix(self, prefix):
cur_node = self.root
for char in prefix:
children = cur_node.children
if char not in children:
return False
else:
cur_node = children[char]
return True