-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathST-PTD.py
82 lines (71 loc) · 2.4 KB
/
ST-PTD.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 10 20:25:07 2022
@author: ruhityagi
"""
import time
class Node:
def __init__(self, sub="", children=None):
self.sub = sub
self.ch = children or []
start= time.time()
class SuffixTree:
def __init__(self, str):
self.nodes = [Node()]
for i in range(len(str)):
self.addSuffix(str[i:])
def addSuffix(self, suf):
n = 0
i = 0
while i < len(suf):
b = suf[i]
x2 = 0
while True:
children = self.nodes[n].ch
if x2 == len(children):
# if no matching child, remainder of suf(suffix) becomes new node
n2 = len(self.nodes)
self.nodes.append(Node(suf[i:], []))
self.nodes[n].ch.append(n2)
return
n2 = children[x2]
if self.nodes[n2].sub[0] == b:
break
x2 = x2 + 1
#time.sleep(5)
# find prefix of remaining suffix in common with child
sub2 = self.nodes[n2].sub
j = 0
while j < len(sub2):
if suf[i + j] != sub2[j]:
# split n2
n3 = n2
# new node for the part in common
n2 = len(self.nodes)
self.nodes.append(Node(sub2[:j], [n3]))
self.nodes[n3].sub = sub2[j:] # old node loses the part in common
self.nodes[n].ch[x2] = n2
break # continue traversing down the tree
j = j + 1
i = i + j # advance past part in common
n = n2 # continue traversing down the tree
def visualize(self):
if len(self.nodes) == 0:
print ("<empty>")
return
def f(n, pre):
children = self.nodes[n].ch
if len(children) == 0:
print ("⤑ ", self.nodes[n].sub)
return
print ("┐", self.nodes[n].sub)
for c in children[:-1]:
print (pre, end="├─",)
f(c, pre + "| ")
print (pre, end="└─",)
f(children[-1], pre + " ")
f(0, "")
end=time.time()
SuffixTree("BANANA$").visualize()
print("Time:",{end-start})