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 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/typesset.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
> 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
inplace 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 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 nonmultiple 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 ;)
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! 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 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
# 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
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 :)
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 nonmultiple 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(t2t1, 3), "s",
round(t3t2, 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(t2t1, 3), "s",
round(t3t2, 3), "s"
Bye,
bearophile
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?
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 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

8 posts
views
Thread by SaltyBoat 
last post: by
 
47 posts
views
Thread by Mike Williams 
last post: by
          