HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Find the integer representing the last sub-string of a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lastthesubfindstringintegerrepresenting

Problem

I came across a question at the 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 cleaner (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)

Solution

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

Code Snippets

>>> find_last = lambda s, t: s.rfind(t)
>>> find_last("aaaa", "a")
3
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

Context

StackExchange Code Review Q#107024, answer score: 5

Revisions (0)

No revisions yet.