递归回文检查 - 调用函数时出现问题

Recursive palindrome check - having issues when recalling the function

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

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

第一个false应该是True。 感谢您的帮助!

重写:

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