Created
May 6, 2018 05:32
-
-
Save marklap/d13af6ff039c75f5c08cc1d8311322c6 to your computer and use it in GitHub Desktop.
longest palindromic substring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' longest_palindromic_substring package ''' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' longest_palindromic_substring finds the longest palindrome substring in a string | |
''' | |
def lpss(s): | |
''' lpss (Longest Palindromic SubString) returns the longest palindrome withing the string | |
Args: | |
s (str): string to search | |
Returns: | |
str: resultant substring; the first longest palindromic substring | |
''' | |
len_s = len(s) | |
l_pal = '' | |
for j in range(1, len_s+1): | |
for i in range(len_s - j+1): | |
ss = s[i:i+j] | |
if ss == ss[::-1] and len(ss) > len(l_pal): | |
l_pal = ss | |
return l_pal |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' test_longest_palindromic_substring tests the longest_palindromic_substring module | |
''' | |
from .longest_palindromic_substring import lpss | |
def test_lpss(): | |
cases = [ | |
('These are not the droids you\'re looking for.', 'ese'), | |
('Ugh, no palindromes!', 'U'), | |
('racecar', 'racecar'), | |
('bananarama', 'anana'), | |
('A but tuba.', 'but tub'), | |
('My mom did eat a pip.', ' mom '), | |
] | |
for s, want in cases: | |
got = lpss(s) | |
assert want == got, 'incorrect palindrome - want: {0}, got: {1}'.format(want, got) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment