473,795 Members | 3,393 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why is this loop heavy code so slow in Python? Possible Project Euler spoilers

I'm pretty new to python, but am very happy with it. As well as using
it at work I've been using it to solve various puzzles on the Project
Euler site - http://projecteuler.net. So far it has not let me down,
but it has proved surprisingly slow on one puzzle.

The puzzle is: p is the perimeter of a right angle triangle with
integral length sides, {a,b,c}. which value of p < 1000, is the
number of solutions {a,b,c} maximised?

Here's my python code:

#!/usr/local/bin/python

solutions = [0] * 1001
p = 0

for a in xrange(1, 1000):
for b in xrange(1, 1000 - a):
for c in xrange(1, 1000 - a - b):
p = a + b + c
if p < 1000:
if a ** 2 + b ** 2 == c ** 2:
solutions[p] += 1

max = 0
maxIndex = 0
index = 0
for solution in solutions:
if solution max:
max = solution
maxIndex = index
index += 1

print maxIndex
It takes 2 minutes and twelve seconds on a 2.4GHz Core2Duo MacBook
Pro. Surprised at how slow it was I implemented the same algorithm in
C:

#include <stdio.h>
#include <stdlib.h>

int main() {
int* solutions = calloc(1000, sizeof(int));

int p;
for(int a = 1; a < 1000; ++a) {
for(int b = 1; b < 1000 - a; ++b) {
for(int c = 1; c < 1000 - a - b; ++c) {
p = a + b + c;
if(p < 1000) {
if(a * a + b * b == c * c) {
solutions[p] += 1;
}
}
}
}
}

int max = 0;
int maxIndex = 0;

for(int i = 0; i < 1000; ++i) {
if(solutions[i] max) {
max = solutions[i];
maxIndex = i;
}
}
printf("%d\n", maxIndex);
return 0;
}
gcc -o 39 -std=c99 -O3 39.c

The resulting executable takes 0.24 seconds to run. I'm not expecting
a scripting language to run faster than native code, but I was
surprised at how much slower it was in this case. Any ideas as to what
is causing python so much trouble in the above code?

Sep 2 '07
25 3808
On 2007-09-02, Martin v. Löwis <ma****@v.loewi s.dewrote:
>>(2) it is a interpretation language
Not quite. It's compiled to byte-code - just like Java (would
you call Java an 'interpreted language' ?)

Python is not implemented like Java. In Java (at least in
HotSpot), the byte code is further compiled to machine code
before execution; in Python, the byte code is interpreted.

Whether this makes Python an interpreter or a compiler, I don't
know.
I'd call it an integrated compiler and virtual machine--a classic
combination.

--
Neil Cerutti
Sep 3 '07 #21
Steven D'Aprano <st***@REMOVE-THIS-cybersource.com .auwrites: A big
question mark in my mind is Lisp, which according to aficionados is
just as dynamic as Python, but has native compilers that generate
code running as fast as highly optimized C. I'm not qualified to
judge whether the lessons learnt from Lisp can be applied to Python,
but in any case Lisp is an old, old language -- only Fortran is
older. The amount of development effort and money put into Lisp
dwarfs that put into Python by possibly a hundred or more.
Writing a simple Lisp compiler is not all that difficult. There's a
chapter in SICP about how to do it, so it's sometimes part of
introductory courses. To get C-like performance you end up having to
rely on user-supplied type declarations and/or type inference, but
even without that you can still do ok. I'd say Lisp is a less dynamic
language than Python. Lisp doesn't have duck typing and doesn't
represent class instance variables as dictionary elements that have to
be looked up at runtime all the time. This maybe even applies to
locals, e.g. in Python if you say

x = 3
print "hello"
y = x + 4

you're possibly not guaranteed that y=7, because you might have bound
sys.stdout to something with a .write method that reaches up the call
stack and messes with the caller's local variables, and if the langref
manual says this is supposed to work, then the compiler has to do it
like CPython. Maybe Python 4.0 will fix some of this stuff.
Sep 3 '07 #22
Thanks for all the answers to my question. I think what I need to take
away from this is that xrange is an object - I thought it was just
some loop construct, and that maths is slow in python - so avoid
pathological looping.I remember the first time I tried Objective-C on
OS X I used the NSNumber class for arithmetic - the results that time
were pretty awful too!
Sep 3 '07 #23
On 3 Sep, 15:39, jwrweather...@g mail.com wrote:
Thanks for all the answers to my question. I think what I need to take
away from this is that xrange is an object
Indeed, but using xrange can be faster than converting your "for"
loops to "while" loops plus a counter; I converted your code to use
the latter arrangement and it was noticeably slower. Perhaps the
repeated invocation of each xrange object's next method is less
expensive than repeatedly obtaining new incremented int objects and
testing them against other int objects.
- I thought it was just some loop construct, and that maths is slow in
python - so avoid pathological looping.
You'd be wise to avoid doing unnecessary work deep within nested loops
in any programming language. Sadly, it's not possible for the compiler
to work out that some calculations can be lifted out of the innermost
loops in Python, since the various guarantees that make such
operations possible in other languages are not offered by Python.
I remember the first time I tried Objective-C on OS X I used the
NSNumber class for arithmetic - the results that time were pretty
awful too!
Obviously, it'd be a fairer test if you used comparable numeric types
in both implementations , but a more capable numeric type would be
overkill for the C implementation of this program, and a less capable
numeric type doesn't exist for Python unless you're willing to use a
dialect such as Pyrex (as others have shown).

Paul

Sep 3 '07 #24
Martin v. Löwis a écrit :
>>(2) it is a interpretation language
Not quite. It's compiled to byte-code - just like Java (would you call
Java an 'interpreted language' ?)

Python is not implemented like Java. In Java (at least in HotSpot),
the byte code is further compiled to machine code before execution;
This is a VM-specific feature.
in Python, the byte code is interpreted.
Idem.
Whether this makes Python an interpreter or a compiler,
I don't know.
This is an old troll^Mdiscussi on !-)

Now IANAL, but AFAIK, the byte-code compilation stage can make a great
difference performances-wide, and for a same language, a byte-compiled
implementation is likely to be faster than a pure-interpreted one, at
least because of the saving on parsing time (please someone correct me
if I'm wrong) ...
Sep 3 '07 #25
On Sep 2, 12:51 pm, jwrweather...@g mail.com wrote:
... right-angled triangle puzzle solver

max = 0
maxIndex = 0
index = 0
for solution in solutions:
if solution max:
max = solution
maxIndex = index
index += 1

print maxIndex
Not that it solves your slowness problem, or has anything to
do with the question you asked :), but you can replace this
last segment of your code with:

print solutions.index (max(solutions) )

--
Paul Hankin

Sep 19 '07 #26

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

Similar topics

5
1509
by: Ognen Duzlevski | last post by:
Hi all, I have rewritten a C program to solve a bioinformatics problem. Portion where most of the time is spent is: def DynAlign(scoremat,insertmat,delmat,tseq,qseq,tlen,qlen): global ONEINDELPENALTY,OPENGAPPENALTY for ndx1 in range(1,tlen+1): for ndx2 in range(1,qlen+1): delmat = Min(delmat+ONEINDELPENALTY, \
3
3065
by: pertheli | last post by:
Hello, I have a large array of pointer to some object. I have to run test such that every possible pair in the array is tested. eg. if A,B,C,D are items of the array, possible pairs are AB, AC, AD, BC and CD. I'm using two nested for loop as below, but it is running very slow whenever I access any data in the second loop.
10
2186
by: Extremest | last post by:
I know there are ways to make this a lot faster. Any newsreader does this in seconds. I don't know how they do it and I am very new to c#. If anyone knows a faster way please let me know. All I am doing is quering the db for all the headers for a certain group and then going through them to find all the parts of each post. I only want ones that are complete. Meaning all segments for that one file posted are there. using System;
28
2641
by: H J van Rooyen | last post by:
Hi, I want to write a small system that is transaction based. I want to split the GUI front end data entry away from the file handling and record keeping. Now it seems almost trivially easy using the sockets module to communicate between machines on the same LAN, so that I want to do the record keeping on one machine.
4
1772
by: nw | last post by:
Hi, I was wondering if someone would be able to give me some comments on the following class structure, it feels to me as if there must be a better way, but I'm unsure what it is, perhaps I should be using multiple inheritance? Basically I have a pure virtual class called Body, this contains a number of integration algorithms which are applied to the Body. Generally only one integration algorithm will be used with a
1
3317
by: luna18 | last post by:
i like to do programming but i am not a computer student.. =) i m trying to write a program to determine a euler circuit.but end up all stuck... i tyr to take the input as graph and if it is a euler circuit it will output an euler circuit. can any1 give me some starting point or hints ? thanks for viewing...
92
3981
by: ureuffyrtu955 | last post by:
Python is a good programming language, but "Python" is not a good name. First, python also means snake, Monty Python. If we search "python" in google, emule, many results are not programming resource. If we search PHP, all results are programming resource. Second, python also means snake, snake is not a good thing in western culture. Many people dislike any things relevant to snake. We must have high regard for the custom.
8
1334
by: fprintf | last post by:
I have been playing with computers since I first learned to program moving shapes on an Atari 800XL in BASIC. After many years of dabbling in programming languages as a hobbyist (I am not a computer scientist or other IT professional), I have never found a way to stick with a language far enough to do anything useful. I learn all about loops and data structures and functions/methods etc. but never get to create a program that will do...
6
2946
by: insirawali | last post by:
Hi all, I have this problem, i need to know is there a way i cn use the data adapter's update method in this scenario. i have 3 tables as below create table table1{ id1 int identity(1,1) Constraint pk_table1 Primary Key,
0
9519
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
10437
Oralloy
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
10214
jinu1996
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
10164
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
10001
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 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...
0
5437
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
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
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
3
2920
bsmnconsultancy
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.