Skip to content

Commit 3a63814

Browse files
Merge pull request #203 from erdenezul/refactor_longest_common_subsequence
refactor longest common subsequence problem
2 parents 8e00180 + 3c4c7eb commit 3a63814

File tree

2 files changed

+30
-48
lines changed

2 files changed

+30
-48
lines changed

Diff for: dynamic_programming/longest common subsequence.py

-48
This file was deleted.

Diff for: dynamic_programming/longest_common_subsequence.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them.
3+
A subsequence is a sequence that appears in the same relative order, but not necessarily continious.
4+
Example:"abc", "abg" are subsequences of "abcdefgh".
5+
"""
6+
def lcs_dp(x, y):
7+
# find the length of strings
8+
m = len(x)
9+
n = len(y)
10+
11+
# declaring the array for storing the dp values
12+
L = [[None] * (n + 1) for i in xrange(m + 1)]
13+
seq = []
14+
15+
for i in range(m + 1):
16+
for j in range(n + 1):
17+
if i == 0 or j == 0:
18+
L[i][j] = 0
19+
elif x[i - 1] == y[ j - 1]:
20+
L[i][j] = L[i - 1][j - 1] + 1
21+
seq.append(x[i -1])
22+
else:
23+
L[i][j] = max(L[i - 1][j], L[i][j - 1])
24+
# L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1]
25+
return L[m][n], seq
26+
27+
if __name__=='__main__':
28+
x = 'AGGTAB'
29+
y = 'GXTXAYB'
30+
print lcs_dp(x, y)

0 commit comments

Comments
 (0)