<jupyter_start><jupyter_text>Question 58 - Longest palindrome substringA palindrome is "a word, phrase, or sequence that reads the same backward as forward." Below are some example palindromes:```    madam    racecar    tat ```Can you write a python function that takes in a string and outputs the longest palindrome? If the string itself is a palindrome, the function would output the original string.<jupyter_code>def test_is_palindrome(f):
    assert f('madam') == True # basic
    assert f('ma dam') == True # ignore whitespace
    assert f('ab cdef') == False # counter example
    assert f('') == True # edge case

def is_palindrome(s):
    s = s.replace(" ", "") # remove whitespaces
    n = len(s)
    if n == 0:
        return True
    differing_chars = sum([s[i] != s[n-i-1] for i in range(n//2)])
    return differing_chars == 0

test_is_palindrome(is_palindrome)


def test_longest_palindrome_substr(lps_func):
    assert lps_func('hello madam irma') == 'madam' # find substr
    assert lps_func('hello ma dam') == 'madam' # ignore spaces
    assert lps_func('aba a ba') == 'abaaba' # longest palindrome is made of 2 smaller ones
    assert lps_func('madam the racecar') == 'racecar' # find longest one, not first one
    assert lps_func('hi welcome') == 'h' # default to first character if no substring of 2+ chars is a palindrome
    assert lps_func('tat') == 'tat' # whole string is longest palindrome
    assert lps_func('') == '' # empty string
    
    
def longest_palindrome_substr(s):
    """ find longest palindrome substring """
    s = s.replace(' ','') # ignore whitespaces
    if s == '':
        return ''
    longest_pal = s[0] # convention: return first char if no substr of len 2+ is palindrome
    
    # for each substring,
    for i in range(len(s)):
        for j in range(i,len(s)):
            ss = s[i:j+1]
            # if it is a palindrome, and longest so far, store it.
            if is_palindrome(ss) and len(ss) > len(longest_pal):
                longest_pal = ss
                
    return longest_pal

test_longest_palindrome_substr(longest_palindrome_substr)

longest_palindrome_substr('hello madam irma')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10714285714285714, 'fraction_numerical': 0.005036630036630037, 'mean_word_length': 3.2927308447937134, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '76978', 'license': 'Unlicense', 'n_tokens_mistral': 706, 'n_tokens_neox': 694, 'n_words': 236, 'path': 'interviewq_exercises/q058_python_longest_palindrome_substring.ipynb', 'repo_name': 'gentimouton/dives', 'size': '2184'}