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 1501 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
> 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.differ ence(deletions)
It's almost not worth calling a function for :) There's also an
in-place version called difference_upda te().
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(r ange(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 ;-)
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(1 000)"
100 loops, best of 3: 14.3 msec per loop
# version from the Cookbook
gregory@home:~$ python -mtimeit "import test1" "test1.primes(1 000)"
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 :-) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Yang Li Ke |
last post by:
Hi guys,
Is it possible to know the internet speed of the visitors with php?
Thanx
--
Yang
|
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
of small related tables
- about two or three visitors at the same time
- hosted on fast and large server in the US
|
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, callable(*args))
return proxy
which, is functionally equivalent to
|
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 almost any operating system? Or is
there many other reasons why?
I understand there is ansi/iso C and C++ and that ANSI/ISO Code will work on
any system
If this is the reason why, than why don't developers create specific Python
Distrubutions...
|
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 studio 2003 .net optimization
were enhanced and that i must gain in performance if I switch to VS
2003 or intel compiler. So I send him the project and he returned a
compiled DLL with VS 2003.
Result : the VS 2003 compiled Dll is slower than the VC6...
| |
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.
|
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?
|
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 using a code
loop and an INSERT INTO query. About 800,000 records of raw text.
Later, I can then loop through and parse these 800,000 strings into
usable data using more code.
The problem I have is that the conversion of the text file, using a...
|
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
Can you check if I'm using the clock() function correctly?
the function is finding the number in the array that is closest to a number given by the user. Here is the code for the pass by value function.
Thanks for the help!
relevant code:
|
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 it can be ten times
slower. Is that correct?
I'm quite competent at writing code myself and so most of my code will be
quite well written, and I don't want to move to vb.net if well written VB6
code is ten times faster. Have I been told the...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
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,...
|
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...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |