Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

longest common subsequence python

# A Naive recursive Python implementation of LCS problem
  
def lcs(X, Y, m, n):
  
    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));
  
  
# Driver program to test the above function
X = "AGGTAB"
Y = "GXTXAYB"
print ("Length of LCS is ", lcs(X, Y, len(X), len(Y)))
Output:
Length of LCS is  4
Following is a tabulated implementation for the LCS problem.


# Dynamic Programming implementation of LCS problem
  
def lcs(X, Y):
    # find the length of the strings
    m = len(X)
    n = len(Y)
  
    # declaring the array for storing the dp values
    L = [[None]*(n + 1) for i in range(m + 1)]
  
    """Following steps build L[m + 1][n + 1] in bottom up fashion
    Note: L[i][j] contains length of LCS of X[0..i-1]
    and Y[0..j-1]"""
    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])
  
    # L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1]
    return L[m][n]
# end of function lcs
  
  
# Driver program to test the above function
X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is ", lcs(X, Y))
Comment

PREVIOUS NEXT
Code Example
Python :: how to append panda columns using loop 
Python :: pytplot arc 
Python :: get local ipv4 
Python :: virtual mic with python 
Python :: tkinter icon 
Python :: time difference between two datetime.time 
Python :: how to make a game in python 
Python :: ascending, descending dict 
Python :: install django in windows 
Python :: python yeild 
Python :: sendgrid django smtp 
Python :: how can i remove random symbols in a dataframe in Pandas 
Python :: python list .remove 
Python :: find max length of list of list python 
Python :: fibonacci sequence in python 
Python :: export some columns to csv pandas 
Python :: python jwt 
Python :: how to use query_params in get_object djangorestframework 
Python :: Convert column as array to column as string before saving to csv 
Python :: python two string equal 
Python :: training linear model sklearn 
Python :: ordered dictionary 
Python :: conda create environment python 3 
Python :: pandas dataframe sort by column 
Python :: convert negative to positive in python 
Python :: how to check encoding of csv 
Python :: range python 
Python :: access class variable from another class python 
Python :: python switch statement 
Python :: how to declare np datetime 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =