New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adds new dynamic programming algorithm #2275
base: master
Changes from all commits
7268d77
840bb09
cf64ab7
dd09d4e
c4cb66e
File filter...
Jump to…
| @@ -0,0 +1,56 @@ | ||
| """ | ||
| Longest Palindromic Subsequence Problem: | ||
| Find the longest sequence of characters from a given input string that | ||
| is the same backwards and forwards | ||
| https://en.wikipedia.org/wiki/Longest_common_subsequence_problem | ||
| """ | ||
|
|
||
|
|
||
| def longest_palindromic_subsequence(s: str, length: int) -> int: | ||
|
||
|
|
||
| """ | ||
| Computes the longest Palindromic sequence of a string | ||
| :param s: str, the string we provide | ||
|
This conversation was marked as resolved
by kishan151999
cclauss
Member
|
||
| :param length: int, the length of the string | ||
|
This conversation was marked as resolved
by kishan151999
cclauss
Member
|
||
| :return L[0][n - 1]: int, the length of the longest Palindromic subsequence | ||
| >>> longest_palindromic_subsequence("ABBCDABBC",9) | ||
| 5 | ||
| >>> longest_palindromic_subsequence("ABACCG",6) | ||
| 3 | ||
| >>> longest_palindromic_subsequence("55055901565109",14) | ||
| 9 | ||
cclauss
Member
|
||
| """ | ||
|
|
||
| # creating an array to store the values generated | ||
| dp_table = [[1 for i in range(length)] for i in range(length)] | ||
cclauss
Member
|
||
|
|
||
| # Filling in the array created | ||
| for x in range(2, length + 1): | ||
| for y in range(length + 1 - x): | ||
| z = y + x - 1 | ||
| if s[y] == s[z] and x == 2: | ||
| dp_table[y][z] = 2 | ||
| elif s[y] == s[z]: | ||
| dp_table[y][z] = dp_table[y + 1][z - 1] + 2 | ||
| else: | ||
| dp_table[y][z] = max(dp_table[y][z - 1], dp_table[y + 1][z]) | ||
|
|
||
| return dp_table[0][length - 1] | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| test_case = "ABAC" | ||
|
|
||
| len_of_test_case = len(test_case) | ||
| print( | ||
| "The longest palindromic subsequence is: " | ||
| + str(longest_palindromic_subsequence(test_case, len_of_test_case)) | ||
| ) | ||
|
|
||
| import doctest | ||
|
|
||
| doctest.testmod() | ||


We should return the sequence, not the length of the sequence. The function is not named
length_of_the_longest_palindromic_subsequence()so I would not expect an int result.The caller can always call
len(result)if they want the length.