python-3.x - 递归回文检查 - 调用函数时出现问题
问题描述
问题很简单,检查是否回文或不使用递归。他们还提供了一个模板,所以我无法更改。模板:
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
第一个假应该是真。谢谢您的帮助!
解决方案
重写它:
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
推荐阅读
- php - 如何在 macOS Catalina 上的 PHP 7.3 下安装 intl 扩展?
- react-native - 使用 Image.getSize 函数反应本机问题
- graphql - GraphQL Stitching - 为什么子模式中的字段会返回 null?
- git - 自动设置多个推送 URL
- laravel - Laravel/nexmo 与 elasticsearch/elasticsearch 冲突您的要求或最低稳定性
- javascript - twbsPagination 不是函数
- python - 有没有更简单的方法来取消数据透视表?
- android - 在整个应用程序上实现使用选择主题,而不是在每个活动上调用 settheme 或重新创建
- javascript - 在 Chart.js 中显示类别相对于堆积条的百分比
- java - 如何同时停止调用 MotionEvent.ACTION_DOWN & MotionEvent.ACTION_UP & MotionEvent.ACTION_MOVE?