I was playing around with a function for an assignment just to better understand it. It was meant to find the last occurrence of a sub-string within a string. The function should return the position of the start of the last occurrence of the sub-string or it must return -1 if the sub-string is not found at all. The ‘standard’ way was as follows:
def find_last(full, sub):
start = -1
while True:
new = full.find(sub, start + 1)
if new == -1:
break
else:
start = new
return start
I wanted to try and have it search in reverse, as this seemed to be the more efficient way. So I tried this:
def find_last(full, sub):
start = -1
while True:
new = full.find(sub, start)
if new == -1 and abs(start) <= len(full): #evals to False when beginning of string is reached
start -= 1
else:
break
return new
We were given a handful of test cases which needed to be passed and my reversed function passed all but one:
print find_last('aaaa', 'a')
>>>3
print find_last('aaaaa', 'aa')
>>>3
print find_last('aaaa', 'b')
>>>-1
print find_last("111111111", "1")
>>>8
print find_last("222222222", "")
>>>8 #should be 9
print find_last("", "3")
>>>-1
print find_last("", "")
>>>0
Can someone kindly explain why find is behaving this way with negative indexing? Or is it just some glaring mistake in my code?
The empty string can be found at any position. Initializing
startwith-1makes your algorithm beginning its search at the penultimate position, not the last.The last position is after the last character of the string, but you are starting to look at the last character of the string.