Alex Rivera | Logout

Recursive Function palindrome in Python

Asked 2009-06-04T17:51:31.243
10

I need help writing a recursive function which detects whether a string is a palindrome. But i can't use any loops it must be recursive. Can anyone help show me how this is done . Im using Python.

Edit
Report

3 Answers

47

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 what's 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 :)

answered 2009-06-04T17:55:26.463
3

Since we're posting code anyway, and no one-liner has been posted yet, here goes:

def palindrome(s):
    return len(s) < 2 or s[0] == s[-1] and palindrome(s[1:-1])
answered 2009-06-04T19:41:57.807
0

My solution

#To solve this I'm using the stride notation within a slice [::]
def amazonPalindrome(input):
    inputB = input
    input = input[::-1]
    #print input
    noPalindrome = inputB + " is not a palindrome"
    isPalindrome = inputB + " is a palindrome"
    #compare the value of the reversed string to input string
    if input[0]!= input[-1]: 
        print noPalindrome
    else:
        print isPalindrome


#invoking the def requires at least 1 value or else it fails
#tests include splitting the string,mixing integers, odd amount palindromes.
#call the def  
amazonPalindrome('yayay')
answered 2011-04-29T07:40:49.120

Your Answer