473,685 Members | 2,719 Online

# improving a huge double-for cycle

Hello there :) ,

I am a python newbie and need to run following code for a task in an
external simulation programm called "Abaqus" which makes use of python
to access the mesh (ensamble of nodes with xy coordinates) of a
certain geometrical model.

[IN is the starting input containing the nodes to be check, there are
some double nodes with the same x and y coordinates which need to be
removed. SN is the output containing such double nodes]

Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
for j in range(len(IN)):
if i <j:
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i].label)

Unfortunately my len(IN) is about 100.000 and the running time about
15h !!!! :(

Any idea to improve it?

I have already tried to group the "if statements" in a single one:

Code: Select all
if i <j and if IN[i].coordinates[0] == IN[j].coordinates[0] and
if IN[i].coordinates[1] == IN[j].coordinates[1]:
but no improvements.

Many thanks, Alex
Sep 18 '08 #1
26 1744

AlexUnfortunate ly my len(IN) is about 100.000 and the running time
Alexabout 15h !!!! :(

AlexAny idea to improve it?

numpy?

http://numpy.scipy.org/
http://www.scipy.org/Numpy_Example_List

More immediately, note that you are building a list of len(IN) ints every
time through the inner loop. A quick hit might be this simple change:

indexes = range(len(IN))
for i in indexes: #scan all elements of the list IN
for j in indexes:
if i != j:
if (IN[i].coordinates[0] == IN[j].coordinates[0] and
IN[i].coordinates[1] == IN[j].coordinates[1]):
SN.append(IN[i].label)

Skip
Sep 18 '08 #2
Alexzive wrote:
Hello there :) ,

I am a python newbie and need to run following code for a task in an
external simulation programm called "Abaqus" which makes use of python
to access the mesh (ensamble of nodes with xy coordinates) of a
certain geometrical model.

[IN is the starting input containing the nodes to be check, there are
some double nodes with the same x and y coordinates which need to be
removed. SN is the output containing such double nodes]

Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
for j in range(len(IN)):
if i <j:
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i].label)

Unfortunately my len(IN) is about 100.000 and the running time about
15h !!!! :(
Any idea to improve it?

I have already tried to group the "if statements" in a single one:

Code: Select all
if i <j and if IN[i].coordinates[0] == IN[j].coordinates[0] and
if IN[i].coordinates[1] == IN[j].coordinates[1]:
but no improvements.

Many thanks, Alex
When you're looking for duplicates an efficient solution is likely to be
based on a set or dict object.

# untested
from collections import defaultdict

groups = defaultdict(lis t)
for item in IN:
c = item.coordinate s
groups[c[0], c[1]].append(item.la bel)
SN = []
for labels in groups.itervalu es():
if len(labels) 1:
SN.extend(label s) # or labels[1:] if you want to keep one item

Peter
Sep 18 '08 #3
Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
for j in range(len(IN)):
if i <j:
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i].label)
Unfortunately my len(IN) is about 100.000 and the running time about
15h !!!! :(

Any idea to improve it?
[snip]
I have already tried to group the "if statements" in a single one:

Code: Select all
if i <j and if IN[i].coordinates[0] == IN[j].coordinates[0] and
if IN[i].coordinates[1] == IN[j].coordinates[1]:

but no improvements.
It's like rearranging deck-chairs on the Titanic :) Yes, it may
give a speed up, but what's 3 seconds when you're waiting 15hr :)

Not knowing the len(IN[x].coordinates) or their structure, if
it's a list of len==2, you should be able to just do

if i <j and IN[i].coordinates == IN[j].coordinates

or

if i <j and IN[i].coordinates[:2] == IN[j].coordinates[:2]

However, again, this is just polish. The big problem is that you
have an O(N^2) algorithm that's killing you.

1) use xrange instead of range to save eating memory with a huge
unneeded array.

2) unless you need to append duplicate labels, you know that when
I and J are swapped, you'll reach the same condition again, so it
might be worth writing the outer loops to eliminate this
scenario, and in the process, but just starting at i+1 rather
than i, you can forgo the check if "i<>j".

Such changes might look something like

for i in xrange(len(IN)) :
for j in xrange(i+1, len(IN)):
if IN[i].coordinates == IN[j].coordinates:
SN.append(IN[i].label)

If my college algorithms memory serves me sufficiently, this
reduces your O(N^2) to O(N log N) which will garner you some
decent time savings.

-tkc
Sep 18 '08 #4
Skip:
indexes = range(len(IN))
for i in indexes: #scan all elements of the list IN
for j in indexes:
Nope, use xrange in both situations, and save a list.
Tim Chase:
for i in xrange(len(IN)) :
for j in xrange(i+1, len(IN)):
if IN[i].coordinates == IN[j].coordinates:
SN.append(IN[i].label)

If my college algorithms memory serves me sufficiently, this
reduces your O(N^2) to O(N log N) which will garner you some
decent time savings.
That's O(n^2) still, it's just half matrix, a triangle.

Bye,
bearophile
Sep 18 '08 #5
On Thu, 18 Sep 2008 05:25:02 -0700, Alexzive wrote:
Hello there :) ,

I am a python newbie and need to run following code for a task in an
external simulation programm called "Abaqus" which makes use of python
to access the mesh (ensamble of nodes with xy coordinates) of a certain
geometrical model.

[IN is the starting input containing the nodes to be check, there are
some double nodes with the same x and y coordinates which need to be
removed. SN is the output containing such double nodes]

Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
for j in range(len(IN)):
if i <j:
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i].label)

Here's a better version of your algorithm, one which avoids the minor
inefficiencies but keeps the huge inefficiency:

for node1 in IN:
for node2 in IN:
if node1 is not node2:
if node1.coordinat es == node2.coordinat es:
SN.append(node1 .label)
This assumes that node.coordinate s is a type where equality is defined.
If they are a tuple or list, that should work fine.

But the huge inefficiency is that you are checking each node not once,
not twice, but 100,000 times! So you have to iterate 10,000,000,000
times, which is going to be slow no matter what you do. Especially in
pure Python.

Here's a better idea: iterate over the list once only:

seen = set()
for node in IN:
coords = tuple(node.coor dinates)
if coords in seen:
SN.append(node. label)
else:
seen.add(coords )

Hope this helps.

--
Steven
Sep 18 '08 #6
Tim Chase:
> for i in xrange(len(IN)) :
for j in xrange(i+1, len(IN)):
if IN[i].coordinates == IN[j].coordinates:
SN.append(IN[i].label)

If my college algorithms memory serves me sufficiently, this
reduces your O(N^2) to O(N log N) which will garner you some
decent time savings.

That's O(n^2) still, it's just half matrix, a triangle.
Ah, good catch as I'm thinking about it more, you're right...it's
O((N^2)/2) which is just O(N^2). Sigh. I'm not awake enough
yet. However, dividing the time by 2 (from 15hr to 7.5hr) is
still a significant savings in my book :)

However, if list-comprehensions are faster as well, you might be
able to do something like

SN = [d.label
for (i,d) in enumerate(IN)
for j in xrange(i+1, len(IN))
if d.coordinates == IN[j].coordinates
]

or the slightly more verbose (but closer to my original code) version

SN = [IN[i].label
for i in xrange(len(IN))
for j in xrange(i+1, len(IN))
if IN[i].coordinates == IN[j].coordinates
]

To the OP: As always, throw some timing code on the various
samples you get back from the list and see what works for you.

-tkc

Sep 18 '08 #7

On Thu, 2008-09-18 at 07:57 -0500, Tim Chase wrote:
Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
for j in range(len(IN)):
if i <j:
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i].label)
Such changes might look something like

for i in xrange(len(IN)) :
for j in xrange(i+1, len(IN)):
if IN[i].coordinates == IN[j].coordinates:
SN.append(IN[i].label)
If you aren't checking j values less than i, you might want to do both

SN.append(IN[i].label)
SN.append(IN[j].label)

on the same pass.

If my college algorithms memory serves me sufficiently, this
reduces your O(N^2) to O(N log N) which will garner you some
decent time savings.

-tkc
--
http://mail.python.org/mailman/listinfo/python-list
Sep 18 '08 #8
On Sep 18, 8:25 am, Alexzive <zasaconsult... @gmail.comwrote :
Hello there :) ,

I am a python newbie and need to run following code for a task in an
external simulation programm called "Abaqus" which makes use of python
to access the mesh (ensamble of nodes with xy coordinates) of a
certain geometrical model.

[IN is the starting input containing the nodes to be check, there are
some double nodes with the same x and y coordinates which need to be
removed. SN is the output containing such double nodes]

Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
for j in range(len(IN)):
if i <j:
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i].label)

Unfortunately my len(IN) is about 100.000 and the running time about
15h !!!! :(

Any idea to improve it?

I have already tried to group the "if statements" in a single one:

Code: Select all
if i <j and if IN[i].coordinates[0] == IN[j].coordinates[0] and
if IN[i].coordinates[1] == IN[j].coordinates[1]:

but no improvements.

Many thanks, Alex

dup=set()
SN=[]
for item in IN:
c=item.coordina tes[0], item.coordinate s[1]
if c in dup:
SN.append(item. label)
else:
dup.add(c)
Sep 18 '08 #9
psyco might help a fair bit (10x-40x) here ;->
perhaps look at dumping the data into sqlite then pulling it back out.
It (or the other databases) are designed for tossing around large lumps
of data.
Alexzive wrote:
Hello there :) ,

I am a python newbie and need to run following code for a task in an
external simulation programm called "Abaqus" which makes use of python
to access the mesh (ensamble of nodes with xy coordinates) of a
certain geometrical model.

[IN is the starting input containing the nodes to be check, there are
some double nodes with the same x and y coordinates which need to be
removed. SN is the output containing such double nodes]

Code: Select all
for i in range(len(IN)): #scan all elements of the list IN
for j in range(len(IN)):
if i <j:
if IN[i].coordinates[0] == IN[j].coordinates[0]:
if IN[i].coordinates[1] == IN[j].coordinates[1]:
SN.append(IN[i].label)

Unfortunately my len(IN) is about 100.000 and the running time about
15h !!!! :(

Any idea to improve it?

I have already tried to group the "if statements" in a single one:

Code: Select all
if i <j and if IN[i].coordinates[0] == IN[j].coordinates[0] and
if IN[i].coordinates[1] == IN[j].coordinates[1]:
but no improvements.

Many thanks, Alex
--
http://mail.python.org/mailman/listinfo/python-list

--

Vapour Forge

Jake Anderson

Project Manager

Mobile: 0412 897 125

Email: ja**@vapourforg e.com

Web Page: www.vapourforge.com

Your source for custom IT services
Sep 18 '08 #10

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

### Similar topics

 8 8099 by: Hans Georg Krauthaeuser | last post by: Dear all, I have a long running application (electromagnetic compatibility measurements in mode-stirred chambers over GPIB) that use pickle (cPickle) to autosave a class instance with all the measured data from time to time. At the beginning, pickling is quite fast but when the data becomes more and more pickling slows down rapidly. 6 3173 by: ad | last post by: I have a huge sting array, there are about 1000 element in it. How can I divide the huge array into small ones, and there are one 10 elements in a small one array? 29 1789 by: Olaf Baeyens | last post by: Because of historical reasons, I have both C# and C++ managed/unmanaged code mixed together in my class library. But I prefer to port code to C# since it compiles faster and the syntax is much more readable so I can do more in less time. The big question now, will I gain/lose performance, given the fact that I create pure managed code, if I port the managed C++ classes to C# classes? I cannot port all the classes at once, too much to... 2 1163 by: Irfan Akram | last post by: Hi Guys, I am in search of some innovative ideas in improving the interface of Online Marking System. At the moment it has some good functionality, but lacks a professional interface. Is there a way of improving the whole interface of the system to make it look consistent as well as professional. Any useful links will be appreciated! Also, how can we copy incorporate the same layout of an existing web-site in 9 1753 by: Vjay77 | last post by: I am working on the program where is necessary to calculate huge amount of numbers in always the same sequence. In other words, these number have to be calculated and saved into memory before the program starts. I was trying to use number pi, but to calculate 100 million decimal places of number pi would take forever and no one would want to wait that long. On the other hand I can't afford to include the whole 100 million dec. places... 5 2295 by: adhag | last post by: Hi I am faced with quite a challenge. I need to open a 70-100 meg file and be able to chunk it out using AJAX back to the client but that isn't my problem really. What I need to do is open the file and get pieces of it out without loading the entire thing into memory. The pieces themselves are random although of a fixed size. If I tried to read an entire file into a stirng and parse pieces out I use too much memory and if I use the... 11 1299 by: perspolis | last post by: Hi all I have a application that connects to a sql server database. I have many rows about above 100,000 records and when I want to fill my sqlDataAdaptor and show results in a grid it takes above 15s,how Can I improve this ?? Is this a good way to fill million of records in fewer time?? thanks in advance 30 2456 by: Alf P. Steinbach | last post by: I once suggested in that SomeOne Else(TM) should propose a string value class that accepted literals and char pointers and so on, with possible custom deleter, and in case of literal strings just carrying the original pointer. In other words, for the simplest usage code: * no overhead (just carrying a pointer or two), and * no possibility of exceptions (for that case). 10 2269 by: Bernhard Reinhardt | last post by: Hi, I read data from a file into a 4 dimensional array. The data has a size of 5MB (could later be up to 500MB). I want to pass the matrix to subroutines. What is the cleverst (and for a beginner easies) way to do so? I read a bit about pointers on the web and in books but the examples do 3 1543 by: Jeff | last post by: ..NET 2.0 I've created a window consisting of a treeview control and a tabcontrol. When a leave in the treeview is clicked then the code should check if the specific tabpage already exists in the tabcontrol and give it focus if it exists. Or else if it doesn't exists then add the tagpage to the tabcontrol. Below is the code which checks if a tabpage already exists and if it does then give it focus... If you have a suggestion on... 0 8507 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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,... 0 9046 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... 0 8926 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... 1 8761 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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,... 0 7589 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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea... 0 5792 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();... 0 4302 by: TSSRALBI | last post by: Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls... 0 4523 by: adsilva | last post by: A Windows Forms form does not have the event Unload, like VB6. What one acts like? 3 1927 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...

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.