ABRAR RAKIN
ABRAR RAKIN

Reputation: 13

What should I do to find the last occurrence of a string?

I am currently taking the Udacity CS101 course (I am a complete beginner). Here is the last quiz of lesson 2: 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 occurences.

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

Here is the code that I wrote:

    def find_last(s,t):
        i=s.find(t)
        if i==-1:
            return -1
        else:
            while True:
                return (s.find(t,i+1))
                i=i+1
            return s.find(t)
    print(find_last('he is','he')

This code does not work for most test cases. For example, here I am expecting an output of 0, but I am getting an output of -1 ('he' definitely exists in 'he is',so the output cannot be -1). Please help.

Upvotes: 1

Views: 432

Answers (4)

Victor
Victor

Reputation: 2919

Counting from the right

Search from the end string. You can use str.rfind() for this:

def find_last(s, t, cheat=True):
   if cheat:
       return s.rfind(t)
   else:
       for i in range(len(s), len(t) - 1, -1):
            if s[i - len(t):i] == t:
                return i-len(t)                
       return -1  

print(find_last('he is he', 'he'))

Output

6

Counting from the left

If you stick to your algo which counts from the left, you can do the following:

def find_last(s,t):
    i = -1
    while True:
        new_i = s.find(t, i + 1)
        if new_i == -1:
            return i
        i = new_i
    return i
print(find_last('aaaa','a'))

Output

3

Upvotes: 4

Mark
Mark

Reputation: 92461

In keeping with your approach of starting at the front and working through the string and assuming you don't just want to use the build-in rfind(), you can loop with index(). It takes a second parameter that tells it where to start looking. This will raise an exception when it can't find the substring, which you can catch and use as a way to end your function. This makes it very succinct and pythonic. You just set the initial index to -1 and update it until it raises that exception:

def find_last(s,t):
    ind = -1
    while True:
        try:
            ind = s.index(t, ind + 1)  
        except ValueError:
            return ind

s = "this_is_a_test"
find_last(s, 'is')
# 4
find_last(s, 't')
# 13
find_last(s, 'z')
# -1

Upvotes: 1

Nandu Raj
Nandu Raj

Reputation: 2110

This should work:

try:
    string ="Hello WorldHello World"
    query = "hey"
    index = string.lower().rindex(query.lower())
except ValueError:
    index = -1
print(index)

Output:

-1

When query was "hello", gave 11

This works even if the string-case is different. Python string method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists. https://www.tutorialspoint.com/python/string_rindex.htm

Upvotes: 2

Sri
Sri

Reputation: 2328

As this is a course, I won't give you an answer. Here is something to consider.

Suppose our string is = "This sentence is a sentence"

Suppose our search term is = "sent"

If you start from the front of the string, you will have to iterate through a large portion of the string. What if you reverse your search term, and search from the back of the string?

Now your search term is "tnes"

If you start from the back of the string, you will be using a for loop with a negative increment.

Upvotes: 4

Related Questions