在PYTHON中使用递归检查回文

2024-09-30 18:17:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在检查一个单词是否是回文,我似乎无法让代码响应。我觉得听起来不错,但显然我遗漏了什么。有人能指出那可能是什么吗?在

def reverse(usrWrd, index):   
    newWord = ""  

    if index == len(usrWrd):
        return newWord
    else:
      newWord += usrWrd[index]
      return reverse(usrWrd, index + 1)

def main(): 
    usrWrd = input("please enter a word to check for palindrome-ness:")

    result = reverse(usrWrd, 0)
    if result == usrWrd:
        print("That word is a palindrome")
    else:
        print("Sorry,",usrWrd,  "is NOT a palindrome")

main()

Tags: indexreturnifismaindefresult单词
3条回答

如前所述局部变量是问题,可能是你可以把局部变量一起发送。典型的尾部递归实现

def reverse(usrWrd, index, newWord=''):

    if index == len(usrWrd):
        return newWord       
    else:
        newWord += usrWrd[index]
        return reverse(usrWrd, index + 1, newWord)

希望有帮助!在

def isPalindrome(s):
   length = len(s);
   if length <= 1:
       return True
   if s[0] != s[length-1]:
       return False
   return isPalindrome(s[1:length-1])

或者对于那些喜欢更简洁代码的人:

^{pr2}$
# Correct approach to your solution
def reverse(usrWrd, index, newWord):
    if index < 0:
        return newWord
    else:
      newWord += usrWrd[index]
      return reverse(usrWrd, index - 1, newWord)

def main():
    newWord = ""
    usrWrd = input("please enter a word to check for palindrome-ness:")
    result = reverse(usrWrd, len(usrWrd) - 1, newWord)

    if result == usrWrd:
        print("That word is a palindrome")
    else:
        print("Sorry,",usrWrd,  "is NOT a palindrome")
############################################################# ^{pr2}$ #############################################################
# Pythonic way as suggested by 'Yaman Jain'
if usrWord == usrWord[::-1]:
    return True # Palindrome
else:
    return False # Not Palindrome

相关问题 更多 >