#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
Run Code Online (Sandbox Code Playgroud)
除了if len(string)>=2 and string[0]==string[-1]:第一个函数和 if string[0]==string[-1] and len(string)>=2:第二个函数中的if条件外,我找不到代码中的差异
在第一个中,首先检查是否有足够的字符进行测试,在第二个中你不要:
if len(string)>=2 and string[0]==string[-1]:
Run Code Online (Sandbox Code Playgroud)
和
if string[0]==string[-1] and len(string)>=2:
Run Code Online (Sandbox Code Playgroud)
并传入一个空字符串:
match_ends(['', 'x', 'xy', 'xyx', 'xx'])
Run Code Online (Sandbox Code Playgroud)
空字符串的长度为0,索引0处没有字符:
>>> len('')
0
>>> ''[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Run Code Online (Sandbox Code Playgroud)
的if布尔表达式被评估左到右,而string[0]==string[-1]在之前的表达进行评价len(string)>=2测试,然后将失败为该空字符串.
在另一个版本中,len(string)>=2首先评估部件,发现是False为空字符串(0不大于或等于2),然后Python根本不需要查看and表达式的另一半,因为有没有机会and表达将成为True下半场评估的任何东西.
请参阅python文档中的布尔表达式:
表达式
x and y首先评估x; 如果x为false,则返回其值; 否则,y将评估并返回结果值.