one line to reverse a string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | f = lambda s:s and f(s[1:])+s[0]
#or
f = lambda s:reduce(lambda a,b:b+a,s,'')
#or
f = lambda s,l=[]:[l.extend(s),l.reverse(),''.join(l)][2]
#after Davids observations I was wondering how come third
#version is slower ...IT can't be as it uses builtin list functions
#that are in C
#then I came to know that in third version default variable l=[] keeps
#its previous info
#try
#f('anurag') twice
#so I changed it to
f = lambda s,l=[[]]:[l.pop(),l.append(list(s)),l[0].reverse(),''.join(l[0])][2]
#now it is the fastest one!!
|
Tags: algorithms
Very nice, but stack use is O( len(string) ). I like your ideas of recursive lambdas although
will usually fail with stack overflow.
how about.
not really a one liner ;)
Second version won't fail. i tried that for f('a'*100000) :)
but that can be done. see third version I have stiched it as a one liner, one liner i mean that can be used in lambda functions
using list for evaluating mutiple expressions is a great techiniqe :)
Cool. Very good solution! By the way i would be interested in your oppinion about my related new recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119596 I actually came to it thinking about your recipe! Good that you didn't have the third solution from the beginning :-)
Maybe you can turn my recipe into a lambda? I just thought, that we might combine our ideas to turn my recipe into lambda functions. I have some ideas and see some problems. we should probably discuss this via email. drop me a note if you are interested to collaborate/discuss holger at trillke net. Or just deliver the lambda :-)
sure. I am just doing that but as it is lot of code it seems slight difficult... ...any way i will try to improve your shortcut :)
if u want to contact me my mail id is anuraguniyal@yahoo.com
Try using list comprehensions. Another way to do this is to use list comprehensions:
or
I find these pretty readable and easy to write. They also perform quite well (clearly better than the others). I will post my test results as a follow up to this. There are some surprises.
Performance surprises. I tested the various flavors of string reverse over the range of 10 to 100,000 character strings with 1 to 100,000 iterations.
List comprehensions win. And there is some very odd behaviour for some of the others. Here is a summary of my observations:
Ok, no suprise there.
Looks ok, except when the string gets large.
Not only does it slow down as the strings get longer, but different iteration counts radically affect the timing in both absolute and per character terms. And not in a predictable way either, look at the 10 character string case which appears to be O(N*iterations) versus the 100 character string case which is O(N) but extremely slow anyway. Something there is that does not like a list... Also, this method seems to improve (relatively) as the string gets very large. Curiouser and curiouser.
(comment continued...)
(...continued from previous comment)
This is twice as fast as any of the other methods and is also quite predictable, taking the same time per character no matter what length string or number of iterations. The alternative comprehension:
was similar, but slightly slower.
Here, for those who wish to play with it, or simply to laugh at my python style is the test program I used:
Ok, no suprise there.
(comment continued...)
(...continued from previous comment)
Looks ok, except when the string gets large.
Not only does it slow down as the strings get longer, but different iteration counts radically affect the timing in both absolute and per character terms. And not in a predictable way either, look at the 10 character string case which appears to be O(N*iterations) versus the 100 character string case which is O(N) but extremely slow anyway. Something there is that does not like a list... Also, this method seems to improve (relatively) as the string gets very large. Curiouser and curiouser.
This is twice as fast as any of the other methods and is also quite predictable, taking the same time per character no matter what length string or number of iterations. The alternative comprehension: <pre> f4 = lambda s: ''.join([s[-1 - i] for i in xrange(len(s))])
Eeeh... I don't know why the add comment procedure insisted on having an extra copy of my post, but it did, I previewed it many times and could never get rid of it...
sigh...
Corrected version is fastest :). See the code above! I have changed third lambda slightly due to some feature of Python which I fail to understand!
f=lambda s:(lambda a:a.reverse()or a.tostring())(__import__('array').array('c', s))
Python 2.3. This recipe is out of date since Python 2.3.
Now you should simply use
reversed_string = s[::-1]
It is much simpler and faster than all solutions mentioned above.