Skip to content

Commit

Permalink
LPS Algorithm is Added Fixed Issues keon#746 (keon#788)
Browse files Browse the repository at this point in the history
* Longest Palindromic Subsequence Algorithm is Added

* test case added

* Renamed
  • Loading branch information
karangadani authored Jun 28, 2021
1 parent 5dde6a0 commit 779bc2f
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ If you want to uninstall algorithms, it is as simple as:
- [hashtable](algorithms/map/hashtable.py)
- [separate_chaining_hashtable](algorithms/map/separate_chaining_hashtable.py)
- [longest_common_subsequence](algorithms/map/longest_common_subsequence.py)
- [longest_palindromic_subsequence](algorithms/map/longest_palindromic_subsequence.py)
- [randomized_set](algorithms/map/randomized_set.py)
- [valid_sudoku](algorithms/map/valid_sudoku.py)
- [word_pattern](algorithms/map/word_pattern.py)
Expand Down
22 changes: 22 additions & 0 deletions algorithms/map/longest_palindromic_subsequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
def longest_palindromic_subsequence(str):
n = len(str)

# Create a table to store results of subproblems
L = [[0 for x in range(n)] for x in range(n)]

for i in range(n):
L[i][i] = 1


for sub_string_length in range(2, n + 1):
for i in range(n-sub_string_length + 1):
j = i + sub_string_length-1
if str[i] == str[j] and sub_string_length == 2:
L[i][j] = 2
elif str[i] == str[j]:
L[i][j] = L[i + 1][j-1] + 2
else:
L[i][j] = max(L[i][j-1], L[i + 1][j]);

return L[0][n-1]

15 changes: 14 additions & 1 deletion tests/test_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
Node, SeparateChainingHashTable,
word_pattern,
is_isomorphic,
is_anagram
is_anagram,
longest_palindromic_subsequence,
)

import unittest
Expand Down Expand Up @@ -164,6 +165,18 @@ def test_is_isomorphic(self):
self.assertFalse(is_isomorphic("foo", "bar"))
self.assertTrue(is_isomorphic("paper", "title"))

class TestLongestPalindromicSubsequence(unittest.TestCase):
def test_longest_palindromic_subsequence_is_correct(self):
self.assertEqual(7,longest_palindromic_subsequence('BBABCBCAB'))
self.assertEqual(4,longest_palindromic_subsequence('abbaeae'))
self.assertEqual(8,longest_palindromic_subsequence('babbbababaa'))
self.assertEqual(6,longest_palindromic_subsequence('daccandeeja'))

def test_longest_palindromic_subsequence_is_incorrect(self):
self.assertEqual(4,longest_palindromic_subsequence('BBABCBCAB'))
self.assertEqual(5,longest_palindromic_subsequence('abbaeae'))
self.assertEqual(2,longest_palindromic_subsequence('babbbababaa'))
self.assertEqual(1,longest_palindromic_subsequence('daccandeeja'))

class TestIsAnagram(unittest.TestCase):
def test_is_anagram(self):
Expand Down

0 comments on commit 779bc2f

Please sign in to comment.