-
Notifications
You must be signed in to change notification settings - Fork 5
/
longestcommonseq.py
64 lines (57 loc) · 1.35 KB
/
longestcommonseq.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
def lcs1(x, y):
'''TODO'''
mlist = []
xlcs = ""
ylcs = ""
last = 0
for i in range(len(x)):
for j in range(len(y[last:])):
if x[i] == y[j + last - 1]:
last = j
xlcs += x[i]
last = 0
for i in range(len(y)):
for j in range(len(x[last:])):
if y[i] == x[j + last - 1]:
last = j
ylcs += y[i]
if len(xlcs) > len(ylcs):
print xlcs
else:
print ylcs
def xlcs(x, y):
xans = ""
if len(x) == 0:
return xans
elif len(x) == 1:
for i in range(len(y)):
if x[0] == y[i]:
xans += y[i]
return xans
else:
for i in range(len(x)):
for j in range(len(y)):
if x[i] == y[j]:
return x[i] + xlcs(x[i+1:], y[j+1:])
return xans
def ylcs(y, x):
xans = ""
if len(y) == 0:
return xans
elif len(y) == 1:
for i in range(len(x)):
if y[0] == x[i]:
xans += x[i]
return xans
else:
for i in range(len(y)):
for j in range(len(x)):
if y[i] == x[j]:
return y[i] + ylcs(y[i+1:], x[j+1:])
return xans
def lcs(x, y):
if len(xlcs(x, y)) > len(ylcs(y, x)):
print xlcs(x, y)
else:
print ylcs(y, x)
lcs("" , "")