Python Forum

Full Version: Python code for Longest Common Subsequence
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am looking for a Python code to find the longest common subsequence of two strings. I found a blog post that describes the problem and provides a solution in Java. I would like to implement the same solution in Python.

The blog post can be found here on longest common subsequence dynamic programming:

The Java code for the longest common subsequence problem is as follows:

python
def longestCommonSubsequence(X, Y):
    m = len(X)
    n = len(Y)
    dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
    for i in range(m + 1):
        for j in range(n + 1):
            if i == 0 or j == 0:
                dp[i][j] = 0
            elif 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])
    return dp[m][n]
Can you help me with this?
What exactly you need help with? There is python code implementation in the article you refer to.

Also, please use proper BBCode tags
Your code looks like a mash up of the bottom-up approach and the dynamic programming approach. Pick one.
(Sep-11-2023, 12:00 PM)buran Wrote: [ -> ]What exactly you need help with? There is python code implementation in the article you refer to.

Also, please use proper BBCode tags

Okay