From 73a212ebd5b4a73f4b33ac1c5089ce67f1a7497e Mon Sep 17 00:00:00 2001 From: Anushka Gupta <100286919+Anushkagpt@users.noreply.github.com> Date: Tue, 8 Oct 2024 20:02:27 +0530 Subject: [PATCH 1/2] Create lcs_algorithm.py --- lcs_algorithm.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 lcs_algorithm.py diff --git a/lcs_algorithm.py b/lcs_algorithm.py new file mode 100644 index 000000000000..0d224f40dbd3 --- /dev/null +++ b/lcs_algorithm.py @@ -0,0 +1,46 @@ +def longest_common_subsequence(X, Y): + """ + Find the longest common subsequence (LCS) between two strings. + + Args: + X (str): First string + Y (str): Second string + + Returns: + str: The longest common subsequence + """ + m = len(X) + n = len(Y) + + # Create a 2D array to store the lengths of common subsequences + dp = [[0] * (n + 1) for _ in range(m + 1)] + + # Fill the 2D array using dynamic programming + for i in range(1, m + 1): + for j in range(1, n + 1): + if X[i - 1] == Y[j - 1]: + dp[i][j] = dp[i - 1][j - 1] + 1 + else: + dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) + + # Reconstruct the LCS from the 2D array + lcs = [] + i, j = m, n + while i > 0 and j > 0: + if X[i - 1] == Y[j - 1]: + lcs.append(X[i - 1]) + i -= 1 + j -= 1 + elif dp[i - 1][j] > dp[i][j - 1]: + i -= 1 + else: + j -= 1 + + # Return the LCS in the correct order + return "".join(reversed(lcs)) + +# Example usage: +X = "AGGTAB" +Y = "GXTXAYB" +lcs = longest_common_subsequence(X, Y) +print(f"The longest common subsequence is: {lcs}") From 72535a17acb7f8a70be0e3a02b7258c6143ddb42 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 8 Oct 2024 14:33:12 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- lcs_algorithm.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lcs_algorithm.py b/lcs_algorithm.py index 0d224f40dbd3..2ac4f6e5db6c 100644 --- a/lcs_algorithm.py +++ b/lcs_algorithm.py @@ -39,6 +39,7 @@ def longest_common_subsequence(X, Y): # Return the LCS in the correct order return "".join(reversed(lcs)) + # Example usage: X = "AGGTAB" Y = "GXTXAYB"