Skip to content

Instantly share code, notes, and snippets.

@marklap
Created May 6, 2018 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marklap/d13af6ff039c75f5c08cc1d8311322c6 to your computer and use it in GitHub Desktop.
Save marklap/d13af6ff039c75f5c08cc1d8311322c6 to your computer and use it in GitHub Desktop.
longest palindromic substring
''' longest_palindromic_substring package '''
''' 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
''' 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