在整个你的函数的功能是: 如果x的长度等于5,返回True 否则,如果字符串的最后一个字符等于第一个返回true, 否则返回False
这种状况别的条件... else返回False最好使用或者只有当所有条件都是False并返回第一个not-False元素的值时才返回False的语句。其他选择是与任何序列基本相同的任何函数。下面这些替代品的所有分支的考试原if语句:
def function(x):
if len(x) == 5: return True
else: return x[0] == x[-1]
def funcor(x):
return (len(x)==5) or (x[0] == x[-1])
def funcany(x):
return any((len(x)==5, x[0] == x[-1]))
def funcverbal(sequence):
## sequence[0] is the first element of zero based indexed sequence
## endswith is string specific function so sequence must be string
## if it's length is not 5
return len(sequence)==5 or sequence.endswith(sequence[0])
## function is normal data type in Python, so we can pass it in as variable
def test(func):
print('Testing %s function' % func)
for value in ('12345','annb','ansa','23424242',('1','2','1'), 123, '131'):
try:
print ("%r -> %r" % (value,func(value)))
except:
print ("Failed to call function with " + repr(value))
print(10 * '-'+'Finished testing '+str(func) + 10 * '-')
for thisfunction in (function, funcor, funcany, funcverbal):
test(thisfunction)
(函数在突出显示为蓝色的保留字,但它是错误的亮点日常在这个网站)
在isPalindrome功能的情况下, ,长度条件不是任意的,但有必要识别原始情况来停止递归,在回文函数的'anna'情况下:
查看'anna'的长度是否小于2( 1或0),不,它们不是 比较'a'和'a',因为它们是相同的 滴出所比较的第一和最后一个字母和呼叫isPalindrome与“N-N”
看看的“N-N”的长度小于2(1或0),没有它们不 比较“N”与“N ',继续,因为它们是相同的 辍学比较的第一个和最后一个字母,并呼吁isPalindrome与''
看看''的长度是否小于2(1或0),是的。当我们找到回文时,返回True。
这是基于回文逆转与回文相同这一事实的回文测试的替代短期函数。
def isPalindrome(s):
return s==s[::-1]
嗨Blaenk,你的回答现在让我明白了。作为初学者,我必须理解短裤的感觉,谢谢你的帮助! – raoulbia 2010-08-26 23:17:46