简体   繁体   English

如何返回对函数的递归调用?

[英]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. 编写一个名为is_palindrome的递归函数,该函数将一个名为word的字符串作为其参数,如果word的长度小于或等于1,则返回True。如果word的长度大于1,则如果word的第一个字符,则该函数应返回False。与单词的最后一个字符不同。 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 (eg is_palindrome("anna") should return the result of is_palindrome("nn")). 如果单词的长度大于1,并且字符串的第一个和最后一个字符相同,则该函数应返回is_palindrome()的结果,并删除单词的第一个和最后一个字符(例如is_palindrome(“ anna “)应该返回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 您需要返回对is_palindrome的递归调用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM