我是编程新手,正在研究Guttag的书“使用Python和应用程序来理解数据的计算和编程简介”。在第4.3.2节的图4.9中,我无法理解他的回文代码。
这在书中给出
def isPalindrome(s):
"""Assumes s is a str
Returns True if s is a palindrome; False otherwise.
Punctuation marks, blanks, and capitalization are ignored."""
def toChars(s):
s = s.lower()
letters = ''
for c in s:
if c in 'abcdefghijklmnopqrstuvwxyz':
letters = letters + c
return letters
def isPal(s):
print(' isPal called with', s)
if len(s) <= 1:
print(' About to return True from base case')
return True
else:
answer = s[0] == s[-1] and isPal(s[1:-1])
print(' About to return', answer, 'for', s)
return answer
return isPal(toChars(s))
def testIsPalindrome():
print('Try dogGod')
print(isPalindrome('dogGod'))
print('Try doGood')
print(isPalindrome('doGood'))
可打印
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
我不明白为什么函数在生成后仍会继续
About to return True from base case
和
About to return False for go
在此先感谢您的解释。