user5405648
user5405648

Reputation:

Finding last substring in string?

I'm trying to code a function to find the last substring in a string. I don't want a solution in any other code, I need to do it using my own procedure for course homework.

Most tests work, although when testing aa in aaaaa it fails. I understand why because its starting from a position with only a left, but how can I fix this?

def find_last(s, c):
    last_position = 0
    result = -1

    while True:
        next_position = s.find(c, last_position)
        if next_position == -1:
            break
        result = next_position
        last_position = next_position + len(c)

    return result

print(find_last("aaaaa", "aa")) # should output 3 but doesn't?

Upvotes: 3

Views: 147

Answers (3)

jingx
jingx

Reputation: 4014

If you are allowed to use built-in functions, you could do this:

idx = s[::-1].find(c[::-1])
return len(s) - (idx + len(c)) if idx >= 0 else -1

Upvotes: 1

Filip Młynarski
Filip Młynarski

Reputation: 3612

It's because you're increasing next_position with length of found substring thus missing last match.

def find_last(s, c):
    last_position = 0
    result = -1

    while True:
        next_position = s.find(c, last_position)
        if next_position == -1:
            break
        result = next_position
        #last_position = next_position + len(c)
        last_position += 1

    return result

print(find_last("aaaaa", "aa")) # -> 3

You could also use built-in python function rindex() which will return first index counting from end of string

print("aaaaa".rindex("aa")) # -> 3

Upvotes: 0

CryptoFool
CryptoFool

Reputation: 23079

Your problem is this line:

last_position = next_position + len(c)

This is skipping potential matches. As it is, your code considers only the first, third, and fifth positions for matches. As you say, the right answer comes from checking the fourth position (index == 3). But you're skipping that because you move the length of the test string each time, rather than moving forward by only one character.

I think you want:

last_position = next_position + 1

Upvotes: 0

Related Questions