recursion – Recursive Function palindrome in Python

recursion – Recursive Function palindrome in Python

def ispalindrome(word):
    if len(word) < 2: return True
    if word[0] != word[-1]: return False
    return ispalindrome(word[1:-1])

And here is the best one liner

def ispalindrome(word):
    return word == word[::-1]

From a general algorithm perspective, the recursive function has 3 cases:

1) 0 items left. Item is a palindrome, by identity.

2) 1 item left. Item is a palindrome, by identity.

3) 2 or more items. Remove first and last item. Compare. If they are the same, call function on whats left of string. If first and last are not the same, item is not a palindrome.

The implementation of the function itself is left as an exercise to the reader 🙂

recursion – Recursive Function palindrome in Python

If a string is zero or one letters long, its a palindrome.

If a string has the first and last letters the same, and the remaining letters (I think its a [1: -1] slice in Python, but my Python is a bit rusty) are a palindrome, its a palindrome.

Now, write that as a palindrome function that takes a string. It will call itself.

Leave a Reply

Your email address will not be published. Required fields are marked *