#i couldnt find the difference in the code
>>> def match_ends(words):
# +++your code here+++
count=0
for string in words:
if len(string)>=2 and string[0]==string[-1]:
count=count+1
return count
>>> match_ends(['', 'x', 'xy', 'xyx', 'xx'])
2
>>>
>>> def match_ends(words):
# +++your code here+++
count=0
for string in words:
if string[0]==string[-1] and len(string)>=2:
count=count+1
return count
>>> match_ends(['', 'x', 'xy', 'xyx', 'xx'])
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
match_ends(['', 'x', 'xy', 'xyx', 'xx'])
File "<pyshell#25>", line 5, in match_ends
if string[0]==string[-1] and len(string)>=2:
IndexError: string index out of range
除了第一个函数中的if条件if len(string)>=2 and string[0]==string[-1]:
和第二个函数中的{
在第一种情况下,首先检查是否有足够的字符进行测试,而在第二种情况下则没有:
以及
^{pr2}$然后传入一个空的字符串:
空字符串的长度为0,索引0处没有字符:
正在从左到右计算
if
布尔表达式,string[0]==string[-1]
表达式在len(string)>=2
测试之前求值,然后对该空字符串失败。在在另一个版本中,首先计算}。在
len(string)>=2
部分,发现空字符串的False
(0不大于或等于2),然后Python根本不需要查看and
表达式的另一半,因为无论第二部分的计算结果如何,and
表达式都不可能变成{请参见python文档中的Boolean expressions:
相关问题 更多 >
编程相关推荐