如果字符串是Palindrome
,则输出测试def isPalindrome1(s):
"""Assume s is an str
Returns True if s is a palindrome;False otherwise.
Punctuation marks, blanks, and capitalization are
ignored."""
def toChars(s):
s = s.lower()# Means:s = 'ABCD',if s referenced by s.lower,then s='abcd'.
ans = ''
for c in s:
if c in'abcdefghijklmnopqrstuvwxyz':
ans =ans+c
return ans
def isPal(s):
print ' isPal called with',s
if len(s)<=1:
print ' About to return True from base case'
return True
else:
ans = s[0] == s[-1] and isPal(s[1:-1])
print ' About to return',ans,'for',s
return ans
return isPal(toChars(s))
def testIspalindrome1():
print 'Try dogGod'
print isPalindrome1('dogGod')
print 'Try doGood'
print isPalindrome1('doGood')
执行函数&#34; testIspalindrome1()&#34;将得到以下结果:
Try dogGod
isPal called with doggod
isPal called with oggo
isPal called with gg
isPal called with
**About to return True from base case
About to return True for gg
About to return True for oggo
About to return True for doggod**
True
Try doGood
isPal called with dogood
isPal called with ogoo
isPal called with go
About to return False for go
About to return False for ogoo
About to return False for dogood
False
星星部分的执行逻辑是什么?
答案 0 :(得分:1)
每次返回递归时,都必须从调用方法的地方继续。
ans = s[0] == s[-1] and isPal(s[1:-1]) # This branches off, like any other function call
print ' About to return',ans,'for',s # This waits for recursion to finish
答案 1 :(得分:0)
逻辑:
这能为你解释逻辑吗?
从基础案例回来
About to return True for gg
来自此代码:
ans = s[0] == s[-1] and isPal(s[1:-1])
print ' About to return',ans,'for',s
让我们看看赋值中的表达式,用它们的值替换符号:
ans = "g" == "g" and True
我们从最后的递归调用中得到最后的True
,其中参数是空字符串。基本案例返回True
,我们在这里使用。
结束字母匹配,中间字母(空字符串)形成回文,因此完整字符串也是回文。因此,我们会将True
返回到上一个电话。
此调用现在使用字符串oggo
进行相同的处理:
and = "o" == "o" and True
......等等,直到我们到达原来的电话。
答案 2 :(得分:0)
**About to return True from base case
About to return True for gg
About to return True for oggo
About to return True for doggod**
这样可以保持从正面和背面移除角色。 并继续检查pallindrome