You are on page 1of 2

08/01/2022, 16:27 DAA EXP-4.

ipynb - Colaboratory

20CS2018L Design and Analysis of Algorithms

Reg No : URK20CS2065

Ex. No:4

Date : 08/01/2021

Name : D ALAN DANIELS

Video Link : https://youtu.be/bd3dPNLxRMg


Longest Common Subsequences using Dynamic Programming

Aim:

To write a program to get the length of the longest common subsequence using dynamic
programming.

Description:

Given two sequences, find the length of longest subsequence present in both of them. A
subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”.

Algorithm:

Function main():

Input two strings from the user and store them in variables s1 and s2.
Calculate the lengths of both the strings and store it in variables l1 and l2.

Function lcs():

Pass the two strings and their respective lengths as the arguments of the function.
Initialize a 2-d array (dp) with row -> (l1+1) and column -> (l2+1)
Iterate through 2-d array dp check if s1[i-1]==s2[j-1] if so assign dp[i][j]=dp[i-1][j-1]+1 else
assign dp[i][j]= max(dp[i-1][j],dp[i][j-1]).
Return dp[l1][l2] which will be the length of the longest common subsequence.

Program:

1
def lcs(s1,s2,l1,l2):

2
    dp=[[0 for i in range(l2+1)] for j in range(l1+1)]

3
    for i in range(1,l1+1):

4
        for j in range(1,l2+1):

5
            if s1[i-1]==s2[j-1]:

6
                dp[i][j]=dp[i-1][j-1]+1

7
            else:

8
                dp[i][j]=max(dp[i-1][j],dp[i][j-1])

https://colab.research.google.com/drive/1sKrDA5R8p3VQ7qBv_3oRZ8guFRe85BdV#scrollTo=Z-_udfS8X-3N&printMode=true 1/3
08/01/2022, 16:27 DAA EXP-4.ipynb - Colaboratory

9
    print("\nTHE TABLE")

10
    for i in dp:

11
        print(i)

12
    print("\nLength of the Longest Common Subsequence:",dp[l1][l2])

13
def main():

14
    s1=input("Enter String1: ")

15
    s2=input("Enter String2: ")

16
    l1=len(s1)

17
    l2=len(s2)

18
    lcs(s1,s2,l1,l2)

19
if __name__=="__main__":

20
    main()

Enter String1: algorithm

Enter String2: alignment

THE TABLE

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 1, 1, 1, 1, 1, 1, 1, 1, 1]

[0, 1, 2, 2, 2, 2, 2, 2, 2, 2]

[0, 1, 2, 2, 3, 3, 3, 3, 3, 3]

[0, 1, 2, 2, 3, 3, 3, 3, 3, 3]

[0, 1, 2, 2, 3, 3, 3, 3, 3, 3]

[0, 1, 2, 3, 3, 3, 3, 3, 3, 3]

[0, 1, 2, 3, 3, 3, 3, 3, 3, 4]

[0, 1, 2, 3, 3, 3, 3, 3, 3, 4]

[0, 1, 2, 3, 3, 3, 4, 4, 4, 4]

Length of the Longest Common Subsequence: 4

Result:

Thus the program to get the longest common subsequence using dynamic programming has been
written and tested for various inputs.

https://colab.research.google.com/drive/1sKrDA5R8p3VQ7qBv_3oRZ8guFRe85BdV#scrollTo=Z-_udfS8X-3N&printMode=true 2/3

You might also like