Search code examples
pythonstringpalindrome

Longest palindrome in a substring of a string


I'm trying to find the longest palindrome in a string and this is my take.

def palindrome(x):
    rev = x[::-1]
    a = False
    if (rev==x):
        a = True
    return a


def longest_palindrome(s):

    last = len(s) 
    lst = []
    for i in range (last):
        for j in range (i+1,last):
            b = s[i] + s[j]
            a = palindrome(b)
            if (a==True):
                lst.append(b)
            else:
                continue
    return lst

a = input("Enter the string: ")
longest_palindrome(a)

If my input is "aaba" it produces the output ['aa','aa','aa'] whereas the output should be ['aa', 'aba']. Is there a problem in the way I'm iterating?


Solution

  • I think the problem in your code is with finding the substrings. Try this

    def palindrome(x):
        if len(x) <= 1: ## This condition checks if the length of the string is 1. And if so, it returns False
            return False
        return x == x[::-1]:
    
    
    def longest_palindrome(s):
    
        last = len(s)
        lst = []
        for i in range(last):
            for j in range(i, last): ## Iterate from i to last not i+1 to last
                b = s[i:j+1]         ## Slicing the original string to get the substring and checking if it is a pallindrome or not.
                if palindrome(b):
                    lst.append(b)
                else:
                    continue
        return lst
    
    a = input("Enter the string: ")
    print(longest_palindrome(a))
    

    . This code will help