[Tutor] Better structure?

Orri Ganel singingxduck at gmail.com
Thu Feb 3 05:23:03 CET 2005


Kent Johnson wrote:

> Jacob S. wrote:
>
>>> Try writing the code to do what lstrip actually does
>>> - its much harder. So the library includes the more
>>> difficult function and lets you code the easy ones.
>>
>>
>>
>> def lstrip(string,chars=' ')
>>    string = list(string)
>>    t = 0
>>    for x in string:
>>        if x in chars:
>>            string.remove(t)
>>        else:
>>            break
>>        t = t+1
>>
>>
>> Okay, so it's not that difficult, 
>
>
> Well, after fixing the obvious syntax error I tried
> print lstrip('abcd', 'abcd')
>
> and got
> Traceback (most recent call last):
>   File "D:\Personal\Tutor\LStrip.py", line 11, in ?
>     print lstrip('abcd', 'abcd')
>   File "D:\Personal\Tutor\LStrip.py", line 6, in lstrip
>     string.remove(t)
> ValueError: list.remove(x): x not in list
>
> so maybe it's not that easy either. Don't forget the unit tests! :-)
>
> Kent
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
Actually, its not all that difficult. Instead of removing characters 
from the list, just replace them with an empty string and return 
''.join(string):

 >>> def lstrip(string,chars=' '):
    string = list(string)
    i = 0
    for x in string:
        if x in chars:
            string[i] = ''
        else:
            break
        i+=1
    return ''.join(string)

 >>> lstrip('abcd','abcd')
''
 >>> 'abcd'.lstrip('abcd')
''
 >>> 'go on long log buddy'.lstrip('gonl ')
'buddy'
 >>> lstrip('go on long log buddy', 'gonl ')
'buddy'
 >>> 'go on long log buddy'.lstrip('gonl')
' on long log buddy'
 >>> lstrip('go on long log buddy', 'gonl')
' on long log buddy'

So its not a brute force thing so much as a change in how you look at it 
that makes it difficult.

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.



More information about the Tutor mailing list