首页 > 解决方案 > 递归回文检查 - 调用函数时出现问题

问题描述

问题很简单,检查是否回文或不使用递归。他们还提供了一个模板,所以我无法更改。模板:

def isPalindrome(s): # Wrapper function
   def isPalindromeRec(s,low,high):
      """ Recursive function which checks if substring s[low ... high]     is palindrome
      returns a True/False value"""

   n = len(s)
   return isPalindromeRec(s,0,n-1)

我快到了,但我认为我无法理解递归究竟是如何工作的。(尤其是递归中的值如何变化)

我的代码:

def isPalindrome(s): # Wrapper function
    def isPalindromeRec(s,low,high):
        if len(s)<=1:
            return True
        else:
            if s[0]==s[len(s)-1]:
                return isPalindromeRec(s[low+1:high],low+1,high-1)
            else:
                return False

    n = len(s)
    return isPalindromeRec(s,0,n-1)
print(isPalindrome("anna"))
print(isPalindrome("civic"))
print(isPalindrome("a"))
print(isPalindrome("tx1aa1xt"))
print(isPalindrome(""))
print(isPalindrome("Civic"))
print(isPalindrome("ab"))

这是输出:

runfile('/Users/Rayan/Desktop/AUB Spring 2019/EECE 230 /HW/Homework 7/Problem2.py', wdir='/Users/Rayan/Desktop/AUB Spring 2019/EECE 230 /HW/Homework 7')
True
True
True
False
True
False
False

第一个假应该是真。谢谢您的帮助!

标签: python-3.xrecursionpalindrome

解决方案


重写它:

def isPalindrome(s):
    def isPalindromeRec(s,low,high):

        if (low == high): 
            return True

        if (s[low] != s[high]) : 
            return False

        if (low < high + 1) : 
            return isPalindromeRec(s, low + 1, high - 1); 

        return True

    n = len(s) 
    if (n == 0) : 
        return True

    return isPalindromeRec(s, 0, n - 1); 

print(isPalindrome("anna"))
print(isPalindrome("civic"))
print(isPalindrome("a"))
print(isPalindrome("tx1aa1xt"))
print(isPalindrome(""))
print(isPalindrome("Civic"))
print(isPalindrome("ab"))

output:
True
True
True
True
True
False
False

推荐阅读