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 15 1614
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>
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
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...
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.
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.
On Thu, 14 Oct 2004 11:16:12 -0400, Darren Dale <dd**@cornell.e du> 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_arra y()
for particle in particles:
result += make_complex_ar ray(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********@gmai l.com
mail: ca********@yaho o.com
Carlos Ribeiro wrote: On Thu, 14 Oct 2004 11:16:12 -0400, Darren Dale <dd**@cornell.e du> 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_arra y() for particle in particles: result += make_complex_ar ray(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.
> 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
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.e du> 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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 this description, feel free to go back to
whatever you were doing before. If you're still here, though, I invite you to
consider the following definition:
partitions = lambda n: ]++x for x in partitions(n-k) for k in
range(1,n)]
As defined...
|
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 see that generator expressions have been added to the language
with 2.4 and I question the need for it. I know that it allows for lazy
evaluation which speeds things up for larger lists but why was it
necessary to add it instead of improving list...
|
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: based on tests run under Python 2.2,
map calls are roughly twice as fast as equivalent for loops, and list
comprehensions are usually very slightly faster than map. This speed
difference owes to the fact that map and list comprehensions run at C...
|
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 original list is
, I want to end up with .
Here is the way I'm doing this now:
def straightforward_collapse(myList):
|
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, is that dict comprehensions don't gain you
>> much at all over the dict() constructor plus a generator expression,
>> e.g.:
>> dict((i, chr(65+i)) for i in range(4))
>
> Sure, but the same holds for list comprehensions: list(i*i for i in
| |
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
> obviously be a Py3k thing, though.
Alex Martelli wrote:
> I fully agree, but the BDFL has already (tentatively, I hope)
> Pronounced that the form will stay in Py3K as syntax sugar for
> list(...). I find that to be a truly hateful prospect, but...
|
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.
===
PEP: xxx
Title: Unification of for-statement and list-comprehension syntax
|
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 namespace with
illegal names (names can't contain brackets). Can't someone come up
with a better hack than this? How about using "_1", "_2", etc, or
actually making "_" a list of lists and using the real first, second,
third elements? This is...
|
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 there a notable difference ?
I only ask because i see it in code samples on the internet and in
books.
thanks for any clarity
sk
|
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 value per pixel, and set it to something else if it
meets or falls below a certain threshold - i.e., a Red value of 0
would be changed to 50.
I've built my list by using a Python Image Library statement akin to
the following:
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |