-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomTrie.py
83 lines (71 loc) · 2.08 KB
/
CustomTrie.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
80
81
82
83
class TrieNode:
def __init__(self,char):
self.char=char
self.childNodes=[]
self.terminal=False
self.values=[]
def subNode(self,char):
if self.childNodes:
for cN in self.childNodes:
if cN.char==char:
return cN
return None
class Trie:
def __init__(self, input_list, ctype=None):
self.root=TrieNode(0)
self.type=ctype
self.input_list=input_list
self.insertAll()
def search(self, str):
current = self.root
for s in str:
if current.terminal:
return True
next = current.subNode(s)
if next == None:
return False
current = next
return current.terminal
def search_value(self, str):
current = self.root
for s in str:
if current.terminal:
return current.values
next = current.subNode(s)
if next == None:
return None
current = next
if current.terminal:
return current.values
return None
def searchAll(self, str):
return_arr = []
current = self.root
for s in str:
if current.terminal:
return_arr+=current.values
next = current.subNode(s)
if next == None:
break
current = next
return return_arr
def insert(self, key, value):
# if self.search(key):
# return current
current = self.root
for s in key:
next = current.subNode(s)
if not next:
current.childNodes.append(TrieNode(s))
next = current.subNode(s)
current=next
current.terminal=True
if value:
current.values.append(value)
return current
def insertAll(self):
for d in self.input_list:
if self.type != None:
self.insert(d['Key'], d['Value'])
else:
self.insert(d, None)