-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtrie_cons.py
More file actions
53 lines (48 loc) · 1.28 KB
/
trie_cons.py
File metadata and controls
53 lines (48 loc) · 1.28 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
# -*- coding: utf-8 -*-
class trieNode(object):
def __init__(self):
#initialize the trieNode
self.data = {}
self.isWord = False
class trie(object):
"""
creat a trie for each index in TCAM mem
put the tire in a TCAM mem list,which
contains the trie and the ip_table_index
"""
def __init__(self):
self.root = trieNode()
def insert(self, word):
"""
insert word into the trie
type word: str
return type: void
"""
if len(word) == 0:
return
node = self.root
for letter in word:
child = node.data.get(letter)
if not child:
node.data[letter] = trieNode()
node = node.data[letter]
node.isWord = True
def search(self,word):
"""
search the word in the trie
type word: str
return type: str
"""
res = ''
temp_res = ''
node = self.root
for letter in word:
child = node.data.get(letter)
if child:
temp_res += letter
if child.isWord:
res = temp_res
node = child
else:
break
return res