On 7/3/2009 3:54 PM Dinesh B Vadhia said...
Thanks Emile / Kent.
The problem I see with this solution is that at each stage it is re-summing the j's instead of retaining a running total which the 'for-loop' method does ie. >>> dd = []
 >>> y = d[0]
 >>> for i, x in enumerate(d):
 >>>        y += x
 >>>        dd.append(y)

As the lists of integers get larger (mine are in the thousands of integers per list) the list comprehension solution will get slower. Do you agree?

Yes, no doubt. Your original post asked only if there was a listcomp solution. There are probably listcomp solutions that are faster too. I've not tried looking.

As a rule though, timing related optimizations are best done once a bottleneck is identified. It certainly doesn't hurt to develop the habit of writing clean efficient code, but I wouldn't normally look for better ways of getting something done once I'd written a working solution. In this case, IIRC, sum is highly efficient and for smaller lists (on today's CPUs small might be 1000's of entries) might work just fine. I wouldn't necessarily assume that the list comp is slower at a certain size without testing. I'd bet the listcomp is faster on short lists, and slower on long lists, but where the dividing line is could only be known by testing. If you're interested, look into the timeit module.

Emile

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to