输出字符串是否是回文输出测试字符串是否是回文测试
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')
执行功能“testIspalindrome1()”,将得到以下结果:
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
什么是执行的逻辑在星星的部分?
'def isPalindrome1(s):return s [:: - 1] == s' –
什么是“秃头字母”?我不明白这个问题。 – Prune
@Prune大胆。错字 –