[Tutor] list comprehension problem

Dinesh B Vadhia dineshbvadhia at hotmail.com
Sat Jul 4 00:54:42 CEST 2009


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?

Dinesh



From: Kent Johnson 
Sent: Friday, July 03, 2009 1:21 PM
To: Dinesh B Vadhia 
Cc: tutor at python.org 
Subject: Re: [Tutor] list comprehension problem


On Fri, Jul 3, 2009 at 3:49 PM, Dinesh B
Vadhia<dineshbvadhia at hotmail.com> wrote:
> d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 1, 6, 3, 5, 6, 11, 1]
>
> and we want:
>
> [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95,
> 96]
> dd = [ sum(d[:j]) for j in range(len(d)) ][1:]
>
> gives:
>
> [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95]

In [9]: [ sum(d[:j+1]) for j in range(len(d)) ]
Out[9]: [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73,
78, 84, 95, 96]

Kent
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090703/6b492261/attachment.htm>


More information about the Tutor mailing list