# The longest common subsequence in Python
# Function to find lcs_algo
def lcs_algo(S1, S2, m, n):
L = [[0 for x in range(n+1)] for x in range(m+1)]
# Building the mtrix in bottom-up way
for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0:
L[i][j] = 0
elif S1[i-1] == S2[j-1]:
L[i][j] = L[i-1][j-1] + 1
else:
L[i][j] = max(L[i-1][j], L[i][j-1])
index = L[m][n]
lcs_algo = [""] * (index+1)
lcs_algo[index] = ""
i = m
j = n
while i > 0 and j > 0:
if S1[i-1] == S2[j-1]:
lcs_algo[index-1] = S1[i-1]
i -= 1
j -= 1
index -= 1
elif L[i-1][j] > L[i][j-1]:
i -= 1
else:
j -= 1
# Printing the sub sequences
print("S1 : " + S1 + "\nS2 : " + S2)
print("LCS: " + "".join(lcs_algo))
S1 = "ACADB"
S2 = "CBDA"
m = len(S1)
n = len(S2)
lcs_algo(S1, S2, m, n)
IyBUaGUgbG9uZ2VzdCBjb21tb24gc3Vic2VxdWVuY2UgaW4gUHl0aG9uCgoKIyBGdW5jdGlvbiB0byBmaW5kIGxjc19hbGdvCmRlZiBsY3NfYWxnbyhTMSwgUzIsIG0sIG4pOgogICAgTCA9IFtbMCBmb3IgeCBpbiByYW5nZShuKzEpXSBmb3IgeCBpbiByYW5nZShtKzEpXQoKICAgICMgQnVpbGRpbmcgdGhlIG10cml4IGluIGJvdHRvbS11cCB3YXkKICAgIGZvciBpIGluIHJhbmdlKG0rMSk6CiAgICAgICAgZm9yIGogaW4gcmFuZ2UobisxKToKICAgICAgICAgICAgaWYgaSA9PSAwIG9yIGogPT0gMDoKICAgICAgICAgICAgICAgIExbaV1bal0gPSAwCiAgICAgICAgICAgIGVsaWYgUzFbaS0xXSA9PSBTMltqLTFdOgogICAgICAgICAgICAgICAgTFtpXVtqXSA9IExbaS0xXVtqLTFdICsgMQogICAgICAgICAgICBlbHNlOgogICAgICAgICAgICAgICAgTFtpXVtqXSA9IG1heChMW2ktMV1bal0sIExbaV1bai0xXSkKCiAgICBpbmRleCA9IExbbV1bbl0KCiAgICBsY3NfYWxnbyA9IFsiIl0gKiAoaW5kZXgrMSkKICAgIGxjc19hbGdvW2luZGV4XSA9ICIiCgogICAgaSA9IG0KICAgIGogPSBuCiAgICB3aGlsZSBpID4gMCBhbmQgaiA+IDA6CgogICAgICAgIGlmIFMxW2ktMV0gPT0gUzJbai0xXToKICAgICAgICAgICAgbGNzX2FsZ29baW5kZXgtMV0gPSBTMVtpLTFdCiAgICAgICAgICAgIGkgLT0gMQogICAgICAgICAgICBqIC09IDEKICAgICAgICAgICAgaW5kZXggLT0gMQoKICAgICAgICBlbGlmIExbaS0xXVtqXSA+IExbaV1bai0xXToKICAgICAgICAgICAgaSAtPSAxCiAgICAgICAgZWxzZToKICAgICAgICAgICAgaiAtPSAxCiAgICAgICAgICAgIAogICAgIyBQcmludGluZyB0aGUgc3ViIHNlcXVlbmNlcwogICAgcHJpbnQoIlMxIDogIiArIFMxICsgIlxuUzIgOiAiICsgUzIpCiAgICBwcmludCgiTENTOiAiICsgIiIuam9pbihsY3NfYWxnbykpCgoKUzEgPSAiQUNBREIiClMyID0gIkNCREEiCm0gPSBsZW4oUzEpCm4gPSBsZW4oUzIpCmxjc19hbGdvKFMxLCBTMiwgbSwgbik=