Search code examples
pythonpython-3.xrecursionpalindrome

How can I return a recursive call to a function?


The task:

Write a recursive function called is_palindrome that takes a string named word as its parameter and returns True if word has length less than or equal to 1. If the length of word is greater than 1, the function should return False if the first character of word is different to the last character of word. If the length of word is greater than 1, and the first and last characters of the string are identical, the function should return the result of is_palindrome() with the parameter of word with its first and last characters removed (e.g. is_palindrome("anna") should return the result of is_palindrome("nn")).

My code:

def is_palindrome(word):
    if len(word) <= 1:
        return True
    if len(word) > 1:
        if word[0] != word[len(word) - 1]:
            return False
        elif word[0] == word[len(word) - 1]:
            return word[1:(len(word) - 1)]

possible_palindrome = input("Enter a word/phrase to check: ")
if is_palindrome(possible_palindrome):
    print(possible_palindrome, "is a palindrome")
else:
    print(possible_palindrome, "is not a palindrome")

Feedback from grading:

You need to return a recursive call to is_palindrome


Solution

  • Check the endpoints of the string (first and last character),if the are equal return the call to the remaining (all characters but the first and last):

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

    Examples:

    >>> is_palindrome("f")
    True
    >>> is_palindrome("foo")
    False
    >>> is_palindrome("foof")
    True