Similar to this other post on a method to check for a palindrome:
http://sdet.us/python-palindrome-test/

I wrote another attempt but using recursion, rather then a loop.

def recur_pali(word):
    last_char = word[(len(word) - 1)]
    first_char = word[0]
    if len(word) > 0:
        if last_char == first_char:
            updated_word = word[1:-1]
            if len(updated_word) > 0:
                return recur_pali(updated_word)
            else:
                print("You have a bouncing baby palindrome")
        else:
            print("Not a palindrome")

In this case I do have some messy nested IF statements… Maybe I can clean that up. Basically I take the word passed in, I check if the word length is greater then 0 (treating a 1 character as a palindrome…)

As long as the word has a length greater then 0, we check if the first and last character are the same.

If they are, we slice out the first and last character using [1:-1].

If the characters are not the same we stop the process and output it’s not a palindrome.

After the slice, I check if the updated word (with the sliced characters) is greater then 0 and if it is… I now return a recursive call back to the method itself with the updated word.

This will continue till the word’s characters are exhausted and then it will return that it was a palindrome.

Leave a Reply

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