Skip to content

Instantly share code, notes, and snippets.

@marklap
Created May 6, 2018 05:32

Revisions

  1. marklap created this gist May 6, 2018.
    1 change: 1 addition & 0 deletions __init__.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    ''' longest_palindromic_substring package '''
    22 changes: 22 additions & 0 deletions longest_palindromic_substring.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    ''' 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
    18 changes: 18 additions & 0 deletions test_longest_palindromic_substring.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    ''' 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)