473,396 Members | 1,997 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

question on list comprehensions

Hi,

I need to replace the following loop with a list comprehension:

res=[0]
for i in arange(10000):
res[0]=res[0]+i

In practice, res is a complex 2D numarray. For this reason, the regular
output of a list comprehension will not work: constructing a list of every
intermediate result will result in huge hits in speed and memory.

I saw this article at ASPN:
http://aspn.activestate.com/ASPN/Coo.../Recipe/204297

def thislist():
"""Return a reference to the list object being constructed by the
list comprehension from which this function is called. Raises an
exception if called from anywhere else.
"""
import sys
d = sys._getframe(1).f_locals
nestlevel = 1
while '_[%d]' % nestlevel in d:
nestlevel += 1
return d['_[%d]' % (nestlevel - 1)].__self__

Could the list comprehension include something like thislist().pop(0), to be
called when len(thislist)>1? (I think this could work, but am having
trouble with the syntax.) Or is there a better way to approach the problem?

Thank you,

Darren
Jul 18 '05 #1
15 1594
Darren Dale wrote:
I need to replace the following loop with a list comprehension:

res=[0]
for i in arange(10000):
res[0]=res[0]+i


why?

</F>

Jul 18 '05 #2
Darren Dale wrote:
Hi,

I need to replace the following loop with a list comprehension:

res=[0]
for i in arange(10000):
res[0]=res[0]+i
res[0] = (10000 * (10000-1))/2.0 ;-)
In practice, res is a complex 2D numarray. For this reason, the regular
output of a list comprehension will not work: constructing a list of every
intermediate result will result in huge hits in speed and memory.


Why do you *need* to replace the for loop with a listcomp? Could you
give more details about what you're doing with the complex array?

Roberto
Jul 18 '05 #3
Fredrik Lundh wrote:
Darren Dale wrote:
I need to replace the following loop with a list comprehension:

res=[0]
for i in arange(10000):
res[0]=res[0]+i


why?

</F>


I explained why in the original post...
Jul 18 '05 #4
Darren Dale wrote:
Fredrik Lundh wrote:
Darren Dale wrote:
I need to replace the following loop with a list comprehension:

res=[0]
for i in arange(10000):
res[0]=res[0]+i


why?

</F>


I explained why in the original post...

or I guess I just implied it. The speedup is critical.
Jul 18 '05 #5
Roberto Antonio Ferreira De Almeida wrote:
Darren Dale wrote:
Hi,

I need to replace the following loop with a list comprehension:

res=[0]
for i in arange(10000):
res[0]=res[0]+i


res[0] = (10000 * (10000-1))/2.0 ;-)
In practice, res is a complex 2D numarray. For this reason, the regular
output of a list comprehension will not work: constructing a list of
every intermediate result will result in huge hits in speed and memory.


Why do you *need* to replace the for loop with a listcomp? Could you
give more details about what you're doing with the complex array?

Roberto

OK. As usual, I am having trouble clearly expressing myself. Sorry about
that. Prepare for some physics:

I am simulating diffraction from an array of particles. I have to calculate
a complex array for each particle, add up all these arrays, and square the
magnitude of the result. If I do a for loop, it takes about 6-8 seconds for
a 2000 element array added up over 250 particles. In reality, I will have
2500 particles, or even 2500x2500 particles.

The list comprehension takes only 1.5 seconds for 250 particles. Already,
that means the time has decreased from 40 hours to 10, and that time can be
reduced further if python is not constantly requesting additionaly memory
to grow the resulting list.

I guess that means that I would like to avoid growing the list and popping
the previous result if possible, and just over-write the previous result.
Jul 18 '05 #6
On Thu, 14 Oct 2004 11:16:12 -0400, Darren Dale <dd**@cornell.edu> wrote:
I am simulating diffraction from an array of particles. I have to calculate
a complex array for each particle, add up all these arrays, and square the
magnitude of the result. If I do a for loop, it takes about 6-8 seconds for
a 2000 element array added up over 250 particles. In reality, I will have
2500 particles, or even 2500x2500 particles.


Can't you just sum them inplace as you calculate every new array, for
each particle? Something like this (pseudo code):

result = make_empty_array()
for particle in particles:
result += make_complex_array(particle)
return square(result)

It does not grow the result array indefinitely.... so it solves your
problem, if that's what you need/want to avoid.

--
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: ca********@gmail.com
mail: ca********@yahoo.com
Jul 18 '05 #7
Carlos Ribeiro wrote:
On Thu, 14 Oct 2004 11:16:12 -0400, Darren Dale <dd**@cornell.edu> wrote:
I am simulating diffraction from an array of particles. I have to
calculate a complex array for each particle, add up all these arrays, and
square the magnitude of the result. If I do a for loop, it takes about
6-8 seconds for a 2000 element array added up over 250 particles. In
reality, I will have 2500 particles, or even 2500x2500 particles.


Can't you just sum them inplace as you calculate every new array, for
each particle? Something like this (pseudo code):

result = make_empty_array()
for particle in particles:
result += make_complex_array(particle)
return square(result)

It does not grow the result array indefinitely.... so it solves your
problem, if that's what you need/want to avoid.


You're example is what I have now, it's what I want to replace.

I am trying to make the operations general, so I can do 1x1, 1xN, and NxN
result arrays. In the case of NxN, the overhead in the for loop can be
small compared to the time required for the array operations. But for a 1x1
result array, the for loop is a huge time sink. I thought it would be nice
to get the speedup of the list comprehension, but see no way to change the
array in place. The list comprehension wants to create a new list instead.

At any rate, I found another way to frame my problem to get the speedup.
It's entirely based on linear algebra operations, no ingenious coding
involved, so I wont share the details. They are pretty mundane.
Jul 18 '05 #8
> OK. As usual, I am having trouble clearly expressing myself. Sorry about
that. Prepare for some physics:

I am simulating diffraction from an array of particles. I have to calculate
a complex array for each particle, add up all these arrays, and square the
magnitude of the result. If I do a for loop, it takes about 6-8 seconds for
a 2000 element array added up over 250 particles. In reality, I will have
2500 particles, or even 2500x2500 particles.

The list comprehension takes only 1.5 seconds for 250 particles. Already,
that means the time has decreased from 40 hours to 10, and that time can be
reduced further if python is not constantly requesting additionaly memory
to grow the resulting list.

I guess that means that I would like to avoid growing the list and popping
the previous result if possible, and just over-write the previous result.


Download scientific python: http://www.scipy.org/
And get your linear algebra on. Using Numeric arrays, the size of the
matrices (because they are matrices) are much smaller than the size of
an equivalent Python list of lists, so memory may stop being a concern.

- Josiah

Jul 18 '05 #9
Why not just use while loops instead of for loops? You dont have to
create a new array each time you want a loop - you can simply use an
index integer.

i = 0
while i < 5000000:
res [0] = res [0] + i
i = i + 1

Takes less than 2 seconds on my laptop.
Darren Dale <dd**@cornell.edu> wrote in message news:<ck**********@news01.cit.cornell.edu>...
Hi,

I need to replace the following loop with a list comprehension:

res=[0]
for i in arange(10000):
res[0]=res[0]+i

In practice, res is a complex 2D numarray. For this reason, the regular
output of a list comprehension will not work: constructing a list of every
intermediate result will result in huge hits in speed and memory.

I saw this article at ASPN:
http://aspn.activestate.com/ASPN/Coo.../Recipe/204297

def thislist():
"""Return a reference to the list object being constructed by the
list comprehension from which this function is called. Raises an
exception if called from anywhere else.
"""
import sys
d = sys._getframe(1).f_locals
nestlevel = 1
while '_[%d]' % nestlevel in d:
nestlevel += 1
return d['_[%d]' % (nestlevel - 1)].__self__

Could the list comprehension include something like thislist().pop(0), to be
called when len(thislist)>1? (I think this could work, but am having
trouble with the syntax.) Or is there a better way to approach the problem?

Thank you,

Darren

Jul 18 '05 #10
Mustafa Demirhan <mu*************@gmail.com> wrote:
Why not just use while loops instead of for loops? You dont have to
create a new array each time you want a loop - you can simply use an
index integer.

i = 0
while i < 5000000:
res [0] = res [0] + i
i = i + 1

Takes less than 2 seconds on my laptop.


Sure, this is fine, but low-level twiddling with indices isn't all that
nice. A compact alternative such as

res[0] = sum(xrange(5000000))

is, IMHO, preferable to your while loop, not so much because it may be
faster, but because it expresses a single design idea ("let's sum the
first 5 million nonnegative integers") very directly, rather than
getting into the low-level implementation details of _how_ we generate
those integers one after the other, and how we sum them up ditto.
Alex
Jul 18 '05 #11
On Sun, 17 Oct 2004 17:13:25 +0200, al*****@yahoo.com (Alex Martelli) wrote:
Mustafa Demirhan <mu*************@gmail.com> wrote:
Why not just use while loops instead of for loops? You dont have to
create a new array each time you want a loop - you can simply use an
index integer.

i = 0
while i < 5000000:
res [0] = res [0] + i
i = i + 1

Takes less than 2 seconds on my laptop.


Sure, this is fine, but low-level twiddling with indices isn't all that
nice. A compact alternative such as

res[0] = sum(xrange(5000000))

is, IMHO, preferable to your while loop, not so much because it may be
faster, but because it expresses a single design idea ("let's sum the
first 5 million nonnegative integers") very directly, rather than
getting into the low-level implementation details of _how_ we generate
those integers one after the other, and how we sum them up ditto.

As I'm sure you know, sum(xrange(n)) is pretty predictable:
for n in xrange(10): ... print n, sum(xrange(n)), n*(n-1)/2
...
0 0 0
1 0 0
2 1 1
3 3 3
4 6 6
5 10 10
6 15 15
7 21 21
8 28 28
9 36 36 n=5000000; print n, sum(xrange(n)), n*(n-1)/2

5000000 12499997500000 12499997500000

Guess where the time and space was consumed ;-)

Regards,
Bengt Richter
Jul 18 '05 #12
Bengt Richter <bo**@oz.net> wrote:
...
i = 0
while i < 5000000:
res [0] = res [0] + i
i = i + 1

Takes less than 2 seconds on my laptop.
Sure, this is fine, but low-level twiddling with indices isn't all that
nice. A compact alternative such as

res[0] = sum(xrange(5000000))

... As I'm sure you know, sum(xrange(n)) is pretty predictable:


Of course (Gauss is said to have proven that theorem in primary school,
to solve just such a summation which the teacher had posed to the class
to get -- the teacher hoped -- some longer time of quiet;-).

If I recall correctly, you can generally find closed-form solutions for
summations of polynomials in i. But I had assumed that the poster meant
his code to stand for the summation of some generic nonpolynomial form
in i, and just wanted to contrast his lower-level approach with a
higher-level and more concise one -- essentially teaching Python, not
number theory;-).
Alex
Jul 18 '05 #13

"Alex Martelli" <al*****@yahoo.com> wrote in message
news:1gltsqx.3sh0uedtr3f0N%al*****@yahoo.com...
If I recall correctly, you can generally find closed-form solutions for
summations of polynomials in i.


Yes, as with integrals, the sum of an nth degree poly is (n+1)th degree.
The n+2 coefficients for the sum from 0 to k can be determined by actually
summing the poly for each of 0 to n+1 and equating the n+2 partial sume to
the result poly (with powers evaluated) to get n+2 equations in n+2
unknowns. Even with integral coefficients in the poly to be summed, the
coefficients are generally non-integral rationals and can get pretty nasty
to calculate, so for exact results, it may well be easier and faster to
write and run a program.

Terry J. Reedy

Jul 18 '05 #14
> Yes, as with integrals, the sum of an nth degree poly is (n+1)th degree.
The n+2 coefficients for the sum from 0 to k can be determined by actually
summing the poly for each of 0 to n+1 and equating the n+2 partial sume to
the result poly (with powers evaluated) to get n+2 equations in n+2
unknowns. Even with integral coefficients in the poly to be summed, the
coefficients are generally non-integral rationals and can get pretty nasty
to calculate, so for exact results, it may well be easier and faster to
write and run a program.

As long as you can solve a k+1 degree polynomial with linear algebra
(via gaussian elimination, etc.), you can find:
sum([i**k for i in xrange(1, n+1)])
... with little issue (if you know the trick).

- Josiah

Jul 18 '05 #15
On Sun, 17 Oct 2004 20:25:54 -0400, "Terry Reedy" <tj*****@udel.edu> wrote:

"Alex Martelli" <al*****@yahoo.com> wrote in message
news:1gltsqx.3sh0uedtr3f0N%al*****@yahoo.com...
If I recall correctly, you can generally find closed-form solutions for
summations of polynomials in i.


Yes, as with integrals, the sum of an nth degree poly is (n+1)th degree.
The n+2 coefficients for the sum from 0 to k can be determined by actually
summing the poly for each of 0 to n+1 and equating the n+2 partial sume to
the result poly (with powers evaluated) to get n+2 equations in n+2
unknowns. Even with integral coefficients in the poly to be summed, the
coefficients are generally non-integral rationals and can get pretty nasty
to calculate, so for exact results, it may well be easier and faster to
write and run a program.

Got curious, so I automated creating a polynomial based on an integer series:
from coeffs import getlambda
getlambda([0,1,2,3]) 'lambda x: x' getlambda([1,2,3]) 'lambda x: x +1' L = [sum(xrange(i)) for i in xrange(1,10)]
L [0, 1, 3, 6, 10, 15, 21, 28, 36] getlambda(L) 'lambda x: (x**2 +x)/2' f = eval(getlambda(L))
[f(x) for x in xrange(9)] [0, 1, 3, 6, 10, 15, 21, 28, 36] L2 = [sum([i**2 for i in xrange(j)]) for j in xrange(1,10)]
L2 [0, 1, 5, 14, 30, 55, 91, 140, 204] f2 = eval(getlambda(L2))
[f2(x) for x in xrange(9)] [0, 1, 5, 14, 30, 55, 91, 140, 204] getlambda(L2) 'lambda x: (2*x**3 +3*x**2 +x)/6'
Now we'll try an arbitrary series: f3 = eval(getlambda([3,1,1,0,3,5]))
[f3(x) for x in xrange(6)] [3, 1, 1, 0, 3, 5] getlambda([3,1,1,0,3,5])

'lambda x: (-1080*x**5 +13200*x**4 -55800*x**3 +98400*x**2 -69120*x +21600)/7200'

Maybe I'll clean it up some time ;-)
It's a simultaneous equation solver using my exact decimal/rational class for math,
and then formatting the lambda expression for the nonzero polynomial coefficients.
Not very tested, but seems to work.

Regards,
Bengt Richter
Jul 18 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Elaine Jackson | last post by:
List comprehensions don't work the way you intuitively expect them to work. I realize many people have no intuitions about how list comprehensions 'should' work, so if you recognize yourself in...
24
by: Mahesh Padmanabhan | last post by:
Hi, When list comprehension was added to the language, I had a lot of trouble understanding it but now that I am familiar with it, I am not sure how I programmed in Python without it. Now I...
9
by: Neuruss | last post by:
I have a doubt regarding list comprehensions: According to Mark Lutz in his book Learning Pyhon: "...there is currently a substantial performance advantage to the extra complexity in this case:...
42
by: Alan McIntyre | last post by:
Hi all, I have a list of items that has contiguous repetitions of values, but the number and location of the repetitions is not important, so I just need to strip them out. For example, if my...
30
by: Steven Bethard | last post by:
George Sakkis wrote: > "Steven Bethard" <steven.bethard@gmail.com> wrote: >> Dict comprehensions were recently rejected: >> http://www.python.org/peps/pep-0274.html >> The reason, of course,...
7
by: Steven Bethard | last post by:
Tom Anderson <twic@urchin.earth.li> wrote: > Sounds good. More generally, i'd be more than happy to get rid of list > comprehensions, letting people use list(genexp) instead. That would >...
6
by: Heiko Wundram | last post by:
Hi all! The following PEP tries to make the case for a slight unification of for statement and list comprehension syntax. Comments appreciated, including on the sample implementation. ===...
6
by: Lonnie Princehouse | last post by:
List comprehensions appear to store their temporary result in a variable named "_" (or presumably "_", "_" etc for nested comprehensions) In other words, there are variables being put into the...
16
by: nephish | last post by:
Hey there, i have been learning python for the past few months, but i can seem to get what exactly a lamda is for. What would i use a lamda for that i could not or would not use a def for ? Is...
7
by: idiolect | last post by:
Hi all - Sorry to plague you with another newbie question from a lurker. Hopefully, this will be simple. I have a list full of RGB pixel values read from an image. I want to test each RGB band...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.