0

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?

2
  • 2
    I know this is homework but it's good to know anyway that real code would just use .rfind() method for this. Commented May 1, 2012 at 1:25
  • @yak wow, that would have been much more to the point, thanks. Commented May 1, 2012 at 15:09

1 Answer 1

3

The empty string can be found at any position. Initializing start with -1 makes 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.

Sign up to request clarification or add additional context in comments.

3 Comments

How should 'start' be properly initialized so to return the expected value of 9?
Silly question... sorry. I think: start = len(full) should do the trick then shouldn't it?
Close. len(full)-1 is the same as -1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.