Python Program to Find Longest Common Subsequence using Dynamic Programming with Bottom-Up Approach

This is a Python program to find longest common subsequence (LCS) of two strings using dynamic programming with bottom-up approach.

Problem Description

A string r is a subsequence of a string s if r can be obtained from s by dropping zero or more characters from s. A string r is a common subsequence of s and t if r is a subsequence of both s and t. A string r is a longest common subsequence (LCS) of s and t if there is no string that is longer than r and is a common subsequence of s and t. The problem is to find an LCS of two given strings.

Problem Solution

1. Two functions are defined, lcs and print_lcs.
2. The function lcs takes two strings u and v as arguments.
3. It creates a 2D table c. c is implemented as a list of lists.
4. c[i][j] will contain the length of an LCS of u[i:] and v[j:] where x[k:] is a substring of string x starting at index k.
5. The function first sets c[i][length of v] = 0 and c[length of u][j] = 0 for all i and j.
6. The other values are computed as c[i][j] = 1 + c[i + 1][j + 1] if u[i] == v[j].
7. If u[i] != v[j], then c[i][j] = max(c[i + 1][j], c[i][j + 1]).
8. It returns the table c.
9. The function print_lcs takes as argument the two strings u, v and the table c as generated above.
10. It prints an LCS of u and v using the table c.

Program/Source Code

Here is the source code of a Python program to find an LCS of two strings using dynamic programming with bottom-up approach. The program output is shown below.

def lcs(u, v):
    """Return c where c[i][j] contains length of LCS of u[i:] and v[j:]."""
    c = [[-1]*(len(v) + 1) for _ in range(len(u) + 1)]
 
    for i in range(len(u) + 1):
        c[i][len(v)] = 0
    for j in range(len(v)):
        c[len(u)][j] = 0
 
    for i in range(len(u) - 1, -1, -1):
        for j in range(len(v) - 1, -1, -1):
            if u[i] == v[j]:
                c[i][j] = 1 + c[i + 1][j + 1]
            else:
                c[i][j] = max(c[i + 1][j], c[i][j + 1])
 
    return c
 
 
def print_lcs(u, v, c):
    """Print one LCS of u and v using table c."""
    i = j = 0
    while not (i == len(u) or j == len(v)):
        if u[i] == v[j]:
            print(u[i], end='')
            i += 1
            j += 1
        elif c[i][j + 1] > c[i + 1][j]:
            j += 1
        else:
            i += 1
 
 
u = input('Enter first string: ')
v = input('Enter second string: ')
c = lcs(u, v)
print('Longest Common Subsequence: ', end='')
print_lcs(u, v, c)
Program Explanation

1. The user is prompted to enter two strings.
2. lcs is called on the two strings to get the table c.
3. print_lcs is called to display an LCS of the two strings.

advertisement
advertisement
Runtime Test Cases
Case 1:
Enter first string: abcbdab
Enter second string: bdcaba
Longest Common Subsequence: bdab
 
Case 2:
Enter first string: secret
Enter second string: ritual
Longest Common Subsequence: rt
 
Case 3:
Enter first string: treehouse
Enter second string: elephant
Longest Common Subsequence: eeh

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.