On Fri, 10 Jul 2009 11:57:21 -0400, Robert Berman
<berma...@cfl.rr.com> wrote:

>I think you are looking for a complex solution.

Hardly.

>How about the following example:
>
>
>In [31]: s1='abcdeefghijkl'  #find last 'e'
>
>In [32]: s2=s1[::-1]    #reverses s1
>
>In [33]: j=s2.find('e') #finds first 'e' in reversed string
>
>In [36]: ind=len(s1)-j-1  #index into s1 where last occurrence of 'e' is
>
>In [37]: ind
>Out[37]: 5
>
>In [38]: s1[ind]
>Out[38]: 'e'
>
>In [39]: s1
>Out[39]: 'abcdeefghijkl' BINGO. Done.
>
>Is that not a bit simpler

I did explain (perhaps at too great a length, or with too many
irrelevancies):

>On Fri, 2009-07-10 at 16:24 +0100, Angus Rodgers wrote:
>> [...]
>> On the earlier occasion:
>> [...]
>> I wrote:
>> [...]
>> def rstrip(s):
>>     return lstrip(s[::-1])[::-1]
>>     # Note: far from maximally efficient (two unnecessary copies!)
>> [...]
>> On the present occasion:
>> [...]
>> I thought I had better err in the opposite direction, so I wrote:
>> [...]
>> def rfindchr(strng, ch):
>>     # Surely there's a neater (but still efficient) way?
>>     n = len(strng)
>>     for i in range(n - 1, -1, -1):
>>         if strng[i] == ch:
>>             return i
>>     return -1

I don't even think that's "complicated" (just ugly and clumsy).

I just wondered if there were some simplifying feature of Python
that I had either forgotten or not learned about yet.  Python code
(even mine!) is usually neater than this.

I know efficiency is not always a major concern (and it certainly
isn't of any practical importance in a toy example like this),
but it seems downright profligate to make a reversed copy of a
string just in order to avoid searching it backwards, and to make
use of a nifty notation like "[::-1]" - even though my own first 
instinct is to do exactly that, to save "development time", and
to make use of a previous solution.
-- 
Angus Rodgers
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to