From 870da93b064c0df432d6343f87439505d546b212 Mon Sep 17 00:00:00 2001 From: Shivang-Agarwal11 <65328598+Shivang-Agarwal11@users.noreply.github.com> Date: Thu, 1 Oct 2020 14:50:58 +0530 Subject: [PATCH] Update LowestCommenSubsequence.py This is the LCS program using recursion. --- LowestCommenSubsequence.py | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/LowestCommenSubsequence.py b/LowestCommenSubsequence.py index e3fced4..14bf547 100644 --- a/LowestCommenSubsequence.py +++ b/LowestCommenSubsequence.py @@ -1,20 +1,14 @@ -def lcs(X, Y): - # find the length of the strings - m = len(X) - n = len(Y) +def lcs(X, Y, m, n): - # declaring the array for storing the dp values - L = [[None]*(n - 1) for i in range(m - 1)] + if m == 0 or n == 0: + return 0; + elif X[m-1] == Y[n-1]: + return 1 + lcs(X, Y, m-1, n-1); + else: + return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); - for i in range(m + 1): - for j in range(n + 1): - if i == 0 or j == 0 : - L[i][j] = 0 - elif X[i-1] == Y[j-1]: - L[i][j] = L[i-1][j-1]+1 - else: - L[i][j] = max(L[i-1][j], L[i][j-1]) - return L[m][n] + +# Driver program to test the above function X = "AGGTAB" Y = "GXTXAYB" -print("Length of LCS is ", lcs(X, Y)) +print ("Length of LCS is ", lcs(X , Y, len(X), len(Y)) )