fork download
  1. # The longest common subsequence in Python
  2.  
  3.  
  4. # Function to find lcs_algo
  5. def lcs_algo(S1, S2, m, n):
  6. L = [[0 for x in range(n+1)] for x in range(m+1)]
  7.  
  8. # Building the mtrix in bottom-up way
  9. for i in range(m+1):
  10. for j in range(n+1):
  11. if i == 0 or j == 0:
  12. L[i][j] = 0
  13. elif S1[i-1] == S2[j-1]:
  14. L[i][j] = L[i-1][j-1] + 1
  15. else:
  16. L[i][j] = max(L[i-1][j], L[i][j-1])
  17.  
  18. index = L[m][n]
  19.  
  20. lcs_algo = [""] * (index+1)
  21. lcs_algo[index] = ""
  22.  
  23. i = m
  24. j = n
  25. while i > 0 and j > 0:
  26.  
  27. if S1[i-1] == S2[j-1]:
  28. lcs_algo[index-1] = S1[i-1]
  29. i -= 1
  30. j -= 1
  31. index -= 1
  32.  
  33. elif L[i-1][j] > L[i][j-1]:
  34. i -= 1
  35. else:
  36. j -= 1
  37.  
  38. # Printing the sub sequences
  39. print("S1 : " + S1 + "\nS2 : " + S2)
  40. print("LCS: " + "".join(lcs_algo))
  41.  
  42.  
  43. S1 = "ACADB"
  44. S2 = "CBDA"
  45. m = len(S1)
  46. n = len(S2)
  47. lcs_algo(S1, S2, m, n)
Success #stdin #stdout 0.04s 9400KB
stdin
Standard input is empty
stdout
S1 : ACADB
S2 : CBDA
LCS: CB