Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions pydatastructs/linear_data_structures/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
'matrix_multiply_parallel',
'counting_sort',
'bucket_sort',
'lcs',
]

def _merge(array, sl, el, sr, er, end, comp):
Expand Down Expand Up @@ -546,3 +547,39 @@ def bucket_sort(array: Array, **kwargs) -> Array:
if _check_type(array, DynamicArray):
array._modify(force=True)
return array
##--------------------------------------------------------##
# 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)]
##The xrange() function in Python is used to generate a sequence of numbers, similar to the range() function. However, xrange() is used only in Python 2. x whereas range() is used in Python 3. x

"""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))
##Output:
##Length of LCS is 4
##------------------------------------------------------------##