Comparing two different solutions to a quiz
<p>I've been going through a course on CS on Udemy, and got a quiz to solve.</p>

<p>Here's what is says:</p>

<blockquote>
  <p>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.</p>
  
  <p><strong>Example</strong>: <code>find_last('aaaa', 'a')</code> returns 3</p>
</blockquote>

<p>The first solution is mine, the last is theirs. My question is, in what ways is theirs better than mine, and how could I think next time when solving this kind of a problem, so I would come to a solution faster and better. (I've spent at least 45 min thinking of a solution). </p>

<pre><code>def find_last(s, t):
    some = s.find(t)
    i = some
    while s.find(t, i) != -1:
        some=s.find(t, i)
        i=i+1
   return some

def find_last(s,t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos+1)
        if pos==-1:
            return last_pos
        last_pos = pos
</code></pre>

<p>Here are the examples:</p>

<pre><code>print find_last('aaaa', 'a') # returns 3
print find_last('aaaaa', 'aa') # returns 3
print find_last('aaaa', 'b') # returns -1
print find_last("111111111", "1") # returns 8
print find_last("222222222", "") # returns 9
print find_last("", "3") # returns -1
print find_last("", "") # returns 0
</code></pre>

<p>No need to code anything, just use python built-in string "right find":</p>

<pre><code>print('aaaa'.rfind('a'))
</code></pre>

<p>result: 3</p>

<pre><code>print('bbbbb'.rfind('a'))
</code></pre>

<p>result: -1</p>

<p>also works for "more-than-1-char" search strings of course</p>

<pre><code>print('bbbxb'.rfind('bx'))
</code></pre>

<p>result: 2</p>

<p>Of course, in most widespread platforms like Linux or Windows, the processing is native: means you can't beat the speed.</p>

<p>Edit: someone kindly suggested to code your <code>find_last</code> in one line. Very nice:</p>

<pre><code>find_last = lambda x,y: x.rfind(y)
</code></pre>

python algorithm