Skip to content

Commit ec4e068

Browse files
committed
Merge pull request prakhar1989#33 from vedangmehta/master
Added LCS and updated README and added tests to /tests
2 parents cb0f2e8 + f20e5ce commit ec4e068

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ Completed
3535
- Binary Search Tree
3636
- Kandane's Algorithm
3737
- Knapsack Problem (0/1 and unbounded)
38+
- Longest Increasing Subsequence
39+
- Longest Common Subsequence
3840
- Prefix Tries
3941
- Stack ADT (with example problems)
4042
- String Reverse

dp/lcs.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""
2+
Problem : https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
3+
"""
4+
5+
def longest_common_subsequence(s1, s2):
6+
# lengths of strings s1 and s2
7+
m, n = len(s1), len(s2)
8+
# to cache the results
9+
cache = [[0 for j in range(n + 1)] for i in range(m + 1)]
10+
for i, character_s1 in enumerate(s1):
11+
for j, character_s2 in enumerate(s2):
12+
if character_s1 == character_s2:
13+
cache[i + 1][j + 1] = cache[i][j] + 1
14+
else:
15+
cache[i + 1][j + 1] = max(cache[i][j + 1], cache[i + 1][j])
16+
# LCS is empty by default
17+
sequence = ""
18+
i, j = m, n
19+
# finding the sequence from cache
20+
while i >= 1 and j >= 1:
21+
if s1[i - 1] == s2[j - 1]:
22+
sequence += s1[i - 1]
23+
i, j = i - 1, j - 1
24+
elif cache[i - 1][j] > cache[i][j - 1]:
25+
i -= 1
26+
else:
27+
j -= 1
28+
# returns the length of LCS along with the sequence itself
29+
return (len(sequence), sequence[::-1])
30+
31+
if __name__ == "__main__":
32+
print(longest_common_subsequence("ABCXYZ","ACBCXZ"))

tests/lcs_test.py

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import unittest
2+
import lcs
3+
4+
class TestLCS(unittest.TestCase):
5+
def test_lcs(self):
6+
self.assertEqual(lcs.longest_common_subsequence("ABCD", "BBDABXYDCCAD"), (4, "ABCD"))
7+
self.assertEqual(lcs.longest_common_subsequence("BANANA", "ATANA"), (4, "AANA"))
8+
self.assertEqual(lcs.longest_common_subsequence("ABCDEFG", "BDGK"), (3, "BDG"))
9+
10+
if __name__ == "__main__":
11+
unittest.main()

0 commit comments

Comments
 (0)