Search code examples
pythonpalindrome

Palindromes function does not work


This is what I have so far. What should I do to get this to work?

def num_pal(nums):
    for x in nums: 
        w=

def pals(x):
    pos=0
    pos1=-1
    for n in x:
        if n[pos]==n[pos1]:
            pos=pos+1
            pos1=pos1-1
            return'true'
        else:
            return'false'

Solution

  • You might try this function:

    def is_palindrome(text):
        return text[:len(text)//2] == text[:(len(text)-1)//2:-1]
    

    Here is example usage for reference:

    >>> is_palindrome('')
    True
    >>> is_palindrome('a')
    True
    >>> is_palindrome('b')
    True
    >>> is_palindrome('aa')
    True
    >>> is_palindrome('ab')
    False
    >>> is_palindrome('ba')
    False
    >>> is_palindrome('bb')
    True
    >>> is_palindrome('aaa')
    True
    >>> is_palindrome('aab')
    False
    >>> is_palindrome('aba')
    True