468,736 Members | 2,196 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,736 developers. It's quick & easy.

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 1320
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 discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

13 posts views Thread by Yang Li Ke | last post: by
4 posts views Thread by WindAndWaves | last post: by
34 posts views Thread by Jacek Generowicz | last post: by
28 posts views Thread by Maboroshi | last post: by
7 posts views Thread by YAZ | last post: by
11 posts views Thread by Jim Lewis | last post: by
6 posts views Thread by Jassim Rahma | last post: by
47 posts views Thread by Mike Williams | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
xarzu
2 posts views Thread by xarzu | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.