pythonalgorithmpalindrome

Simple function to check whether a word is palindrome or not


I'm still new to python. It'll be really helpful if someone can point out what's wrong in the code here.

def palindrome(s):
    for i in range(0, len(s)):
        x = (s[i] == s[-1-i])
        if x == True:
            return x
        else:
            x = False
            return x
            break
def palindrome(s):
    for i in range(0, len(s)):
        x = (s[i] == s[-1-i])
        if x == True:
            return x
        else:
            return x
            break
palindrome('loll')

Using this function returns True instead of False.


Solution

  • You're always returning on the first iteration of your loop. This means the loop only executes once. If the first and last letter are equal it will determine you have a palindrome.

    But you can only short-circuit on finding a mis-match, so you should only return early in this situation. Should the loop end without an early return we know we have a valid palindrome, so we can safely return True.

    def palindrome(s):
        for i in range(0, len(s)):
            x = (s[i] == s[-1-i])
            if not x:
                return False
        return True
    

    But you really only need to iterate halfway, and assigning to x is unnecessary.

    def palindrome(s):
        for i in range(0, len(s) // 2):
            if s[i] != s[-1-i]:
                return False
        return True
    

    To further refine this, all implements this kind of short-circuiting, and we can feed it a generator expression.

    def palindrome(s):
        return all(
            s[i] == s[-1 - i]
            for i in range(len(s) // 2)
        )