Speed up this code?

A

aomighty

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
 
B

Ben Cartwright

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.html#SECTION007400000000000000000

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
 
T

Tim Chase

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
 
P

Paul Rubin

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 ;-)
 
A

aomighty

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!
 
K

Kent Johnson

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
 
F

Frank Millman

If you are interested in such programs, you can take a look at this one
too:
http://aspn.activestate.com/ASPN/Cookbook/Python/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
 
G

Gregory Petrosyan

# 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
 
J

John Machin

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 :)
 
B

bearophileHUGS

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:
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
 
J

John Machin

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?
 
F

Frank Millman

Gregory said:
# 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,128
Latest member
ElwoodPhil
Top