Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I came across a question at Udacity Intro to Computer Science course:

Define a procedure, find_last, that takes as input two strings, a search string and a target string, and returns the last position in the search string where the target string appears, or -1 if there are no occurrences.

Example: find_last('aaaa', 'a') returns 3

I think there should be a much clean (shorter, fewer words) way of writing this function:

    def find_last(s, t):
        count = 0
        if s.find(t) >= 0:
            while s.find(t, count + 1) >= 0:
                count += 1
            return count
        else:
            return s.find(t)
share|improve this question

migrated from superuser.com 2 days ago

This question came from our site for computer enthusiasts and power users.

    
consider leveraging the ability to traverse lists backward in python. if you are looking for the last, its always the first if you go backward, and then you can just convert the index to output by adding the negative index to the strings length. just a thought. – Frank Thomas 2 days ago

2 Answers 2

Well the short answer would be str.rfind().

>>> find_last = lambda s, t: s.rfind(t)
>>> find_last("aaaa", "a")
3

Though I'm not sure how much you're required to implement yourself. (Does the task allow usage of .find() at all?) Maybe it could be written like this:

def find_last(s, t):
    start = 0
    while True:
        if s.find(t, start) < 0:
            return start - 1
        start += 1

def find_last(s, t):
    for i in range(len(s)-len(t), -1, -1):
        if s[i:i+len(t)] == t:
            return i
    return -1
share|improve this answer

If you look closely, the logic can be simplified a bit:

def find_last(s, t):
    count = -1
    while s.find(t, count + 1) >= 0:
        count += 1
    return count

This is shorter, and one unnecessary operation is eliminated too. But as the other answer points out, it's questionable whether you're allowed to use find at all in the exercise.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.