I have a recursive solution to the longest common subsequence problem of two strings given below:
def LCS(i, j, lcs): # i , j are the position of character in X and Y respectively which are being compared
# lcs is the string storing the current longest common subsequence
print(i, j, lcs)
if i == 0 or j == 0: # basic case
return lcs
if X[i - 1] == Y[j - 1]: # increment lcs
lcs = X[i - 1] + lcs
return lcs
# else check for LCS(i-1,j) and LCS(i,j-1)
lcs_copy = str(lcs)
lcs1 = LCS(i - 1, j, lcs_copy)
x = len(lcs1)
lcs_copy = str(lcs)
lcs2 = LCS(i, j - 1, lcs_copy)
y = len(lcs2)
if x > y:
lcs = lcs1
else:
lcs = lcs2
return lcs
X = 'abcbddab'
Y = 'bdcaba'
lcs = ''
lcs = LCS(8, 6, lcs)
print(lcs)
but it doesn't give the desired result. any suggestion where might be the issue?