#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
I couldn’t find the difference in the code except the if condition if len(string)>=2 and string[0]==string[-1]: in the first function and if string[0]==string[-1] and len(string)>=2: in the second function
In the first, you first check if there are enough characters to test against, in the second you don’t:
and
and pass in an empty string:
The empty string has length 0, and no character at index 0:
The
ifboolean expression is being evaluated left-to-right, and thestring[0]==string[-1]expression is evaluated before thelen(string)>=2test, and then fails for that empty string.In the other version, the
len(string)>=2part is evaluated first, found to beFalsefor the empty string (0 is not greater or equal to 2) and Python then doesn’t need to look at the other half of theandexpression at all, since there is no chance theandexpression will becomeTruewhatever the second half evaluates to.See Boolean expressions in the python documentation: