Update longest common subsequence.py

This commit is contained in:
Mayank Kumar Jha 2017-08-30 23:03:48 +05:30 committed by GitHub
parent 0e857d8905
commit aae156252f

View File

@ -3,16 +3,46 @@ LCS Problem Statement: Given two sequences, find the length of longest subsequen
A subsequence is a sequence that appears in the same relative order, but not necessarily continious. A subsequence is a sequence that appears in the same relative order, but not necessarily continious.
Example:"abc", "abg" are subsequences of "abcdefgh". Example:"abc", "abg" are subsequences of "abcdefgh".
""" """
def LCS(s1, s2): def LCS(x,y):
m = len(s1) b=[[] for j in range(len(x)+1)]
n = len(s2) c=[[] for i in range(len(x))]
for i in range(len(x)+1):
b[i].append(0)
for i in range(1,len(y)+1):
b[0].append(0)
for i in range(len(x)):
for j in range(len(y)):
if x[i]==y[j]:
b[i+1].append(b[i][j]+1)
c[i].append('/')
elif b[i][j+1]>=b[i+1][j]:
b[i+1].append(b[i][j+1])
c[i].append('|')
else :
b[i+1].append(b[i+1][j])
c[i].append('-')
return b,c
arr = [[0 for i in range(n+1)]for j in range(m+1)]
for i in range(1,m+1): def print_lcs(x,c,n,m):
for j in range(1,n+1): n,m=n-1,m-1
if s1[i-1] == s2[j-1]: ans=[]
arr[i][j] = arr[i-1][j-1]+1 while n>=0 and m>=0:
else: if c[n][m]=='/':
arr[i][j] = max(arr[i-1][j], arr[i][j-1]) ans.append(x[n])
return arr[m][n] n,m=n-1,m-1
elif c[n][m]=='|':
n=n-1
else:
m=m-1
ans=ans[::-1]
return ans
if __name__=='__main__':
x=['a','b','c','b','d','a','b']
y=['b','d','c','a','b','a']
b,c=LCS(x,y)
print('Given \nX : ',x)
print('Y : ',y)
print('LCS : ',print_lcs(x,c,len(x),len(y)))