Skip to content

Commit aae1562

Browse files
author
Mayank Kumar Jha
authored
Update longest common subsequence.py
1 parent 0e857d8 commit aae1562

File tree

1 file changed

+41
-11
lines changed

1 file changed

+41
-11
lines changed

dynamic_programming/longest common subsequence.py

+41-11
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,46 @@
33
A subsequence is a sequence that appears in the same relative order, but not necessarily continious.
44
Example:"abc", "abg" are subsequences of "abcdefgh".
55
"""
6-
def LCS(s1, s2):
7-
m = len(s1)
8-
n = len(s2)
6+
def LCS(x,y):
7+
b=[[] for j in range(len(x)+1)]
8+
c=[[] for i in range(len(x))]
9+
for i in range(len(x)+1):
10+
b[i].append(0)
11+
for i in range(1,len(y)+1):
12+
b[0].append(0)
13+
for i in range(len(x)):
14+
for j in range(len(y)):
15+
if x[i]==y[j]:
16+
b[i+1].append(b[i][j]+1)
17+
c[i].append('/')
18+
elif b[i][j+1]>=b[i+1][j]:
19+
b[i+1].append(b[i][j+1])
20+
c[i].append('|')
21+
else :
22+
b[i+1].append(b[i+1][j])
23+
c[i].append('-')
24+
return b,c
925

10-
arr = [[0 for i in range(n+1)]for j in range(m+1)]
1126

12-
for i in range(1,m+1):
13-
for j in range(1,n+1):
14-
if s1[i-1] == s2[j-1]:
15-
arr[i][j] = arr[i-1][j-1]+1
16-
else:
17-
arr[i][j] = max(arr[i-1][j], arr[i][j-1])
18-
return arr[m][n]
27+
def print_lcs(x,c,n,m):
28+
n,m=n-1,m-1
29+
ans=[]
30+
while n>=0 and m>=0:
31+
if c[n][m]=='/':
32+
ans.append(x[n])
33+
n,m=n-1,m-1
34+
elif c[n][m]=='|':
35+
n=n-1
36+
else:
37+
m=m-1
38+
ans=ans[::-1]
39+
return ans
40+
41+
42+
if __name__=='__main__':
43+
x=['a','b','c','b','d','a','b']
44+
y=['b','d','c','a','b','a']
45+
b,c=LCS(x,y)
46+
print('Given \nX : ',x)
47+
print('Y : ',y)
48+
print('LCS : ',print_lcs(x,c,len(x),len(y)))

0 commit comments

Comments
 (0)