[Tutor] Efficiency
Steven D'Aprano
steve at pearwood.info
Sat Jun 25 17:42:34 CEST 2011
naheed arafat wrote:
> 1)
>>>> zip('How are you?'.split(' ')[::-1],'i am fine.'.split(' '))
> [('you?', 'i'), ('are', 'am'), ('How', 'fine.')]
>>>> map(lambda i,j:(i,j),'How are you?'.split(' ')[::-1],'i am
> fine.'.split(' '))
> [('you?', 'i'), ('are', 'am'), ('How', 'fine.')]
>
> Which one has better efficiency?
Define "efficiency".
Do you mean:
- most efficient for the programmer to write?
- easiest to read?
- fastest for the compiler to compile?
- uses the smallest number of characters in source code?
- takes up the least space on disk when compiled?
- runs fastest?
- uses least memory?
- easiest to maintain when you need to make changes?
- easiest to debug when you discover a bug?
Before trying to optimize your code, you should consider whether you are
wasting your time or not. Chances are good that you are. You should
consider these famous quotes about optimization:
"More computing sins are committed in the name of efficiency (without
necessarily achieving it) than for any other single reason - including
blind stupidity." - W.A. Wulf
"We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil. Yet we should not pass
up our opportunities in that critical 3%. A good programmer will not be
lulled into complacency by such reasoning, he will be wise to look
carefully at the critical code; but only after that code has been
identified." - Donald Knuth
"Bottlenecks occur in surprising places, so don't try to second guess
and put in a speed hack until you have proven that's where the
bottleneck is." - Rob Pike
"The First Rule of Program Optimization: Don't do it. The Second Rule of
Program Optimization (for experts only!): Don't do it yet." - Michael A.
Jackson
I believe that the only efficiency you should care about initially is
the efficiency of *reading* (and to a lesser extent, writing) good,
readable, easily maintained code. So long as you avoid common-sense
mistakes, who cares if you can speed up your script from 2.5
milliseconds to 1.5 ms? Who is going to notice?
(On the other hand, if your script really is too slow, that's a
different story!)
> 2)
> 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(' '))))
That will work well for small amounts of data, say, a few hundred words
or so. But for large amounts of data, it will be slow and inefficient.
It's best to avoid such one-liners when possible, they tend to be slow.
I would solve it like this:
import itertools
a = reversed('How are you'.split(' '))
b = 'I am fine'.split(' ')
words = itertools.chain(*zip(a, b))
' '.join(words)
--
Steven
More information about the Tutor
mailing list