-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBA9A.py
57 lines (48 loc) · 1.64 KB
/
BA9A.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
class TrieNode(object):
def __init__(self,fp=0,pos=1,c=None,word=None):
self.children = []
self.fp = fp
self.pos = pos
self.c = c
class Trie(object):
def __init__(self):
self.root = TrieNode()
self.maxpos = 1
self.nodelist = []
def add(self, s):
"""Add a string to this trie."""
p = self.root
n = len(s)
if self.maxpos == 1:#first word
for i in range(n):
self.maxpos += 1
new_node = TrieNode(fp=p.pos, pos=self.maxpos, c=s[i],word = s[:i])
self.nodelist.append(new_node)
p.children.append(new_node)
p = new_node
else:#other word
for i in range(n):
if s[i] not in [node.c for node in p.children]:
self.maxpos += 1
new_node = TrieNode(fp=p.pos, pos=self.maxpos, c=s[i])
self.nodelist.append(new_node)
p.children.append(new_node)
p = new_node
else:
for node in p.children:#find the fathernode
if s[i] == node.c:
p = node
def addlist(self,wordlists):
for word in wordlists:
self.add(word)
def show(self):
"""Judge where s is in this trie."""
for one in self.nodelist:
print(str(one.fp-1)+'->'+str(one.pos-1)+':'+one.c)
if __name__ == '__main__':
trie = Trie()
listbox = []
for line in open('rosalind_ba9a.txt'):
listbox.append(line.rstrip())
trie.addlist(listbox)
trie.show()