[Tutor] Efficiency

Peter Otten __peter__ at web.de
Sat Jun 25 20:05:38 CEST 2011


naheed arafat wrote:

> Is there any way easier to do the following?
> input:
> 'How are you'
> 'I am fine'
> output:
> 'you I are am How fine'
> 
> solution:
>>>> ' '.join(reduce(lambda x,y:x+y, zip('How are you'.split(' ')[::-1],
> 'I am fine'.split(' '))))

reversed(items) instead of items[::-1] generates the items on the fly.
Other building blocks may be sum() and itertools.chain:

>>> z = zip([1,2,3], "abc")
>>> wanted = reduce(lambda x, y: x + y, z)

>>> sum(z, ()) == wanted
True

>>> from itertools import chain
>>> tuple(chain.from_iterable(z)) == wanted
True




More information about the Tutor mailing list