473,387 Members | 1,455 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,387 software developers and data experts.

Speed up this code?

I'm creating a program to calculate all primes numbers in a range of 0
to n, where n is whatever the user wants it to be. I've worked out the
algorithm and it works perfectly and is pretty fast, but the one thing
seriously slowing down the program is the following code:

def rmlist(original, deletions):
return [i for i in original if i not in deletions]

original will be a list of odd numbers and deletions will be numbers
that are not prime, thus this code will return all items in original
that are not in deletions. For n > 100,000 or so, the program takes a
very long time to run, whereas it's fine for numbers up to 10,000.

Does anybody know a faster way to do this? (finding the difference all
items in list a that are not in list b)?

Thanks,
Martin

May 26 '06 #1
13 1472
ao******@gmail.com wrote:
I'm creating a program to calculate all primes numbers in a range of 0
to n, where n is whatever the user wants it to be. I've worked out the
algorithm and it works perfectly and is pretty fast, but the one thing
seriously slowing down the program is the following code:

def rmlist(original, deletions):
return [i for i in original if i not in deletions]

original will be a list of odd numbers and deletions will be numbers
that are not prime, thus this code will return all items in original
that are not in deletions. For n > 100,000 or so, the program takes a
very long time to run, whereas it's fine for numbers up to 10,000.

Does anybody know a faster way to do this? (finding the difference all
items in list a that are not in list b)?


The "in" operator is expensive for lists because Python has to check,
on average, half the items in the list. Use a better data structure...
in this case, a set will do nicely. See the docs:

http://docs.python.org/lib/types-set.html
http://docs.python.org/tut/node7.htm...00000000000000

Oh, and you didn't ask for it, but I'm sure you're going to get a dozen
pet implementations of prime generators from other c.l.py'ers. So
here's mine. :-)

def primes():
"""Generate prime numbers using the sieve of Eratosthenes."""
yield 2
marks = {}
cur = 3
while True:
skip = marks.pop(cur, None)
if skip is None:
# unmarked number must be prime
yield cur
# mark ahead
marks[cur*cur] = 2*cur
else:
n = cur + skip
while n in marks:
# x already marked as multiple of another prime
n += skip
# first unmarked multiple of this prime
marks[n] = skip
cur += 2

--Ben

May 26 '06 #2
> def rmlist(original, deletions):
return [i for i in original if i not in deletions]

original will be a list of odd numbers and deletions will be numbers
that are not prime, thus this code will return all items in original
that are not in deletions. For n > 100,000 or so, the program takes a
very long time to run, whereas it's fine for numbers up to 10,000.

Does anybody know a faster way to do this? (finding the difference all
items in list a that are not in list b)?


Testing for membership in an unsorted list is an O(n) sort of
operation...the larger the list, the longer it takes.

I presume order doesn't matter, or that the results can be sorted
after the fact. If this is the case, it's quite efficient to use
sets which provide intersection/difference/union methods. If you
pass in sets rather than lists, you can simply

return original.difference(deletions)

It's almost not worth calling a function for :) There's also an
in-place version called difference_update().

Once you've found all the results you want, and done all the set
differences you want, you can just pass the resulting set to a
list and sort it, if sorted results matter.

-tkc


May 26 '06 #3
ao******@gmail.com writes:
Does anybody know a faster way to do this? (finding the difference all
items in list a that are not in list b)?

a = [3, 7, 16, 1, 2, 19, 13, 4, 0, 8] # random.sample(range(20),10)
b = [15, 11, 7, 2, 0, 3, 9, 1, 12, 16] # similar
sorted(set(a)-set(b))
[4, 8, 13, 19]


but you probably don't want to use that kind of implementation.

Here's a version using generators:

def sieve_all(n = 100):
# yield all primes up to n
stream = iter(xrange(2, n))
while True:
p = stream.next()
yield p
def s1(p, stream):
# yield all non-multiple of p
return (q for q in stream if q%p != 0)
stream = s1(p, stream)

# print all primes up to 100
print list(sieve_all(100))

It's cute, but horrendous once you realize what it's doing ;-)
May 26 '06 #4
I got it working using difference() and sets, thanks all! 100,000 takes
about 3 times the time of 10,000, which is what my math buddies told me
I should be getting, rather than an exponential increase :). Thanks,
all!

May 26 '06 #5
ao******@gmail.com wrote:
I'm creating a program to calculate all primes numbers in a range of 0
to n, where n is whatever the user wants it to be. I've worked out the
algorithm and it works perfectly and is pretty fast, but the one thing
seriously slowing down the program is the following code:

def rmlist(original, deletions):
return [i for i in original if i not in deletions]

original will be a list of odd numbers and deletions will be numbers
that are not prime, thus this code will return all items in original
that are not in deletions. For n > 100,000 or so, the program takes a
very long time to run, whereas it's fine for numbers up to 10,000.

Does anybody know a faster way to do this? (finding the difference all
items in list a that are not in list b)?


- Make deletions a set, testing for membership in a set is much faster
than searching a large list.

- Find a better algorithm ;)

Kent
May 26 '06 #6
If you are interested in such programs, you can take a look at this one
too:
http://aspn.activestate.com/ASPN/Coo.../Recipe/366178

It requires more memory, but it's quite fast.

Bye,
bearophile

May 26 '06 #7

be************@lycos.com wrote:
If you are interested in such programs, you can take a look at this one
too:
http://aspn.activestate.com/ASPN/Coo.../Recipe/366178

It requires more memory, but it's quite fast.

Bye,
bearophile


I compared the speed of this one (A) with the speed of Paul Rubin's
above (B).

Primes from 1 to 100 -
A - 0.000118
B - 0.000007

Primes from 1 to 200 -
A - 0.000224
B - 0.000008

Primes from 1 to 300 -
A - 0.000278
B - 0.000008

Nice one, Paul.

Frank Millman

May 26 '06 #8
# Paul Rubin's version
gregory@home:~$ python -mtimeit "import test2" "test2.primes(1000)"
100 loops, best of 3: 14.3 msec per loop

# version from the Cookbook
gregory@home:~$ python -mtimeit "import test1" "test1.primes(1000)"
1000 loops, best of 3: 528 usec per loop

May 26 '06 #9
On 26/05/2006 11:25 PM, Frank Millman wrote:
be************@lycos.com wrote:
If you are interested in such programs, you can take a look at this one
too:
http://aspn.activestate.com/ASPN/Coo.../Recipe/366178

It requires more memory, but it's quite fast.

Bye,
bearophile


I compared the speed of this one (A) with the speed of Paul Rubin's
above (B).

Primes from 1 to 100 -
A - 0.000118
B - 0.000007

Primes from 1 to 200 -
A - 0.000224
B - 0.000008

Primes from 1 to 300 -
A - 0.000278
B - 0.000008

Nice one, Paul.

Frank Millman


Nice one, Frank.

Go back and read Paul's code. Read what he wrote at the bottom: """It's
cute, but horrendous once you realize what it's doing ;-) """
Pax Heisenberg, it is innately horrendous, whether observers realise it
or not :-)
May 26 '06 #10
I have tried this comparison, with a version I've modified a bit, I
have encoutered a problem in sieve_all, for example with n=10000, I
don't know why:

def sieve_all(n=100):
# yield all primes up to n
stream = iter(xrange(2, n))
while True:
p = stream.next()
yield p
def s1(p, stream):
# yield all non-multiple of p
return (q for q in stream if q%p != 0)
stream = s1(p, stream)
def primes(n):
"primes(n): return a list of prime numbers <=n."
# Recipe 366178 modified and fixed
if n == 2:
return [2]
elif n<2:
return []
s = range(3, n+2, 2)
mroot = n ** 0.5
half = len(s)
i = 0
m = 3
while m <= mroot:
if s[i]:
j = (m*m - 3) / 2
s[j] = 0
while j < half:
s[j] = 0
j += m
i += 1
m = 2 * i + 3
if s[-1] > n:
s[-1] = 0
return [2] + filter(None, s)

from time import clock
pmax = 21

for p in xrange(12, pmax):
n = 2 ** p
t1 = clock()
primes(n)
t2 = clock()
list(sieve_all(n))
t3 = clock()
print "primes(2^%s= %s):" % (p, n), round(t2-t1, 3), "s",
round(t3-t2, 3), "s"

import psyco
psyco.bind(primes)
psyco.bind(sieve_all)

for p in xrange(12, pmax):
n = 2 ** p
t1 = clock()
primes(n)
t2 = clock()
list(sieve_all(n))
t3 = clock()
print "primes(2^%s= %s):" % (p, n), round(t2-t1, 3), "s",
round(t3-t2, 3), "s"
Bye,
bearophile

May 26 '06 #11
On 27/05/2006 6:57 AM, be************@lycos.com wrote:
I have tried this comparison, with a version I've modified a bit, I
have encoutered a problem in sieve_all, for example with n=10000, I
don't know why:


It might have been better use of bandwidth to give details of the
problem instead of all that extraneous source code.

Did you get this: """RuntimeError: maximum recursion depth exceeded"""?

You don't know why?

May 26 '06 #12

Gregory Petrosyan wrote:
# Paul Rubin's version
gregory@home:~$ python -mtimeit "import test2" "test2.primes(1000)"
100 loops, best of 3: 14.3 msec per loop

# version from the Cookbook
gregory@home:~$ python -mtimeit "import test1" "test1.primes(1000)"
1000 loops, best of 3: 528 usec per loop


You are quite right, Gregory, my timings are way off.

I have figured out my mistake. Paul's function is a generator. Unlike a
normal function, when you call a generator function, it does not
actually run the entire function, it simply returns a generator object.
It only runs when you iterate over it until it is exhausted. I was
effectively measuring how long it took to *create* the generator, not
iterate over it.

Thanks for correcting me.

Frank

May 27 '06 #13
Hello Martin,

You can use gmpy (http://gmpy.sourceforge.net/)

def primes():
n = 2
while 1:
yield long(n)
n = gmpy.next_prime(n)

HTH,
Miki
http://pythonwise.blogspot.com/

May 28 '06 #14

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

Similar topics

13
by: Yang Li Ke | last post by:
Hi guys, Is it possible to know the internet speed of the visitors with php? Thanx -- Yang
4
by: WindAndWaves | last post by:
Hi Gurus I am building my first ever PHP site. Should I worry about speed? These are the parameters of my site - MySQL database with about 500 records (about 50 fields each) and a couple...
34
by: Jacek Generowicz | last post by:
I have a program in which I make very good use of a memoizer: def memoize(callable): cache = {} def proxy(*args): try: return cache except KeyError: return cache.setdefault(args,...
28
by: Maboroshi | last post by:
Hi I am fairly new to programming but not as such that I am a total beginner From what I understand C and C++ are faster languages than Python. Is this because of Pythons ability to operate on...
7
by: YAZ | last post by:
Hello, I have a dll which do some number crunching. Performances (execution speed) are very important in my application. I use VC6 to compile the DLL. A friend of mine told me that in Visual...
11
by: Jim Lewis | last post by:
Has anyone found a good link on exactly how to speed up code using pyrex? I found various info but the focus is usually not on code speedup.
6
by: Jassim Rahma | last post by:
I want to detect the internet speed using C# to show the user on what speed he's connecting to internet?
8
by: SaltyBoat | last post by:
Needing to import and parse data from a large PDF file into an Access 2002 table: I start by converted the PDF file to a html file. Then I read this html text file, line by line, into a table...
11
by: blackx | last post by:
I'm using clock() to measure the speed of my code (testing the speed of passing by value vs passing by reference in function calls). The problem is, the speed returned by my code is always 0.0000000...
47
by: Mike Williams | last post by:
I'm trying to decide whether or not I need to move to a different development tool and I'm told that VB6 code, when well written, can be ten times faster than vb.net, but that if its badly written...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...

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.