Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!newsfeed.xs4all.nl!newsfeed4.news.xs4all.nl!xs4all!post.news.xs4all.nl!not-for-mail Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.014 X-Spam-Evidence: '*H*': 0.97; '*S*': 0.00; 'pop': 0.05; 'indexing': 0.07; 'reject': 0.07; 'smallest': 0.07; 'wednesday,': 0.07; 'collapsed': 0.09; 'item,': 0.09; 'subject:number': 0.09; 'cc:addr :python-list': 0.11; 'python': 0.11; 'def': 0.12; 'question.': 0.14; 'dictionary,': 0.16; 'heap': 0.16; 'heapq': 0.16; 'inserting': 0.16; 'iterating': 0.16; 'lambda': 0.16; 'mechanism.': 0.16; 'sorting': 0.16; 'subject:Prime': 0.16; 'subject:generator': 0.16; 'true:': 0.16; 'sender:addr:gmail.com': 0.17; 'wrote:': 0.18; 'bit': 0.19; 'trying': 0.19; 'basically': 0.19; 'thu,': 0.19; '>>>': 0.22; 'import': 0.22; 'cc:addr:python.org': 0.22; "haven't": 0.24; 'cc:2**0': 0.24; 'push': 0.26; 'header:In-Reply-To:1': 0.27; 'function': 0.29; 'chris': 0.29; 'on,': 0.29; 'am,': 0.29; 'involving': 0.30; 'message-id:@mail.gmail.com': 0.30; '(which': 0.31; 'code': 0.31; 'getting': 0.31; 'tuples': 0.31; 'thanks!': 0.32; 'run': 0.32; 'quite': 0.32; 'worked': 0.33; "i'd": 0.34; 'could': 0.34; 'something': 0.35; 'but': 0.35; 'received:google.com': 0.35; 'there': 0.35; 'version': 0.36; 'really': 0.36; 'module.': 0.36; 'yield': 0.36; 'next': 0.36; "didn't": 0.36; 'thanks': 0.36; 'should': 0.36; 'changing': 0.37; 'list': 0.37; 'performance': 0.37; 'minimum': 0.38; 'saves': 0.38; 'star': 0.38; 'list,': 0.38; 'does': 0.39; 'skip:u 10': 0.60; 'course.': 0.60; 'removing': 0.60; 'new': 0.61; 'happen': 0.63; 'july': 0.63; 'skip:n 10': 0.64; 'more': 0.64; 'total': 0.65; 'to:addr:gmail.com': 0.65; 'series': 0.66; 'bulk': 0.74; 'jul': 0.74; 'prime': 0.74; 'actually,': 0.84; 'dict.': 0.84; 'experiment': 0.84; 'hood': 0.84; "it'd": 0.84; 'moves': 0.84; 'ridiculously': 0.84; '1:47': 0.91; 'severe': 0.91; 'imagine': 0.93; '2013': 0.98 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=mime-version:sender:in-reply-to:references:from:date :x-google-sender-auth:message-id:subject:to:cc:content-type :content-transfer-encoding; bh=VIkAakhr2vPQ8V8oOdelij/wize5f94/rxJ13V2yhtY=; b=l94hbWbz6p7ZjA9X1VzogJErro5wjo8T7QZrerlPzdYyZpg7azadxtuSbFAJuJTN0g GLkBNx8mUqLJNADN9mavaGLmcplj6MwbKZf6MCHMahOUHDl4JIgtBGx+o/AHddXWPGub PxEkz/5OhRwnajuIeTdybgzuFAn1ySe8qJyTDfYhBlz98vVsG6EvW40uYM65CNEsrwa+ ATlZSZS7v0UfrxxIBSG4l7CkzEBjIDM+lb99u8pZ0QHs2ZE/Kp2IT6uIyM5lTZqb9H3k ujY6bKHQ8TekH2dEPjOnbnU+XzPspvehFVIwQTzL2C5WNald9Vjr/mT9/rud23JE9UHN vmRw== X-Received: by 10.152.42.171 with SMTP id p11mr15376319lal.79.1373478472156; Wed, 10 Jul 2013 10:47:52 -0700 (PDT) MIME-Version: 1.0 Sender: joshua.landau.ws@gmail.com In-Reply-To: References: <15167633-b6e7-46cc-a043-8dfe8aaad11e@googlegroups.com> From: Joshua Landau Date: Wed, 10 Jul 2013 18:47:11 +0100 X-Google-Sender-Auth: 6ox4tOMbi12GYfQpm7pS3I_rXG4 Subject: Re: Prime number generator To: Chris Angelico Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Cc: python-list X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.15 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Newsgroups: comp.lang.python Message-ID: Lines: 78 NNTP-Posting-Host: 2001:888:2000:d::a6 X-Trace: 1373478479 news.xs4all.nl 15954 [2001:888:2000:d::a6]:42444 X-Complaints-To: abuse@xs4all.nl Xref: csiph.com comp.lang.python:50384 On 10 July 2013 17:15, Chris Angelico wrote: > On Thu, Jul 11, 2013 at 1:47 AM, bas wrote: >> On Wednesday, July 10, 2013 5:12:19 PM UTC+2, Chris Angelico wrote: >>> Well, that does answer the question. Unfortunately the use of lambda >>> there has a severe performance cost [ ...] >> If you care about speed, you might want to check the heapq module. Remov= ing the smallest item and inserting a new item in a heap both cost O(log(N)= ) time, while finding the minimum in a dictionary requires iterating over t= he whole dictionary, which cost O(N) time. Actually, because it's a list under the hood I'd imagine push and pop still take O(n) time :/. > Ehh, speed isn't the ultimate. I was just trying to avoid something > that worked out ridiculously slow (a Python function call IS quite > slow). I haven't profiled the code to find out where the bulk of the > time is spent, but switching in the lambda-based version doubled total > run time, so I didn't like it :) > >> (untested) >> #before loop >> from heapq import * >> primes =3D [(2,2)] #heap of tuples (multiple, prime). start with 1 item,= so no need for heapify >> >> #during loop >> smallest, prm =3D heappop(primes) >> heappush(primes, (smallest+prm, prm)) >> >> #when new prime found >> heappush(primes, (i+i, i)) > > Ahh, that's the bit I should have thought of! Of course. > > My original thought experiment had involved basically a really long > list, like the classic Sieve but getting longer as time moves on, with > composites replaced by None and primes with their next-markers, which > I then collapsed to a dict. Always I was thinking in terms of indexing > with the prime to get its next composite. Here's the code involving > heapq: > > # -- start -- > def primes(): > """Generate an infinite series of prime numbers.""" > from heapq import heappush,heappop > i=3D2 > yield 2 > prime=3D[(2,2)] # Heap > while True: > smallest, prm =3D heappop(prime) > heappush(prime, (smallest+prm, prm)) > while i yield i > heappush(prime, (i+i, i)) > i+=3D1 > if i=3D=3Dsmallest: i+=3D1 > > gen=3Dprimes() > print([next(gen) for i in range(10)]) > for i in range(1000): > next(gen) # Star Trek? > print("The next prime number is:",next(gen)) > # -- end -- > > And that's significantly shorter, clearer, AND faster than the original. = Thanks! AFAICT, that's exactly my code but using a less-efficient storage medium and a *much* more efficient sorting mechanism. It'd be interesting what could happen if heapq didn't reject blists -- they have better efficiency for changing list sizes (which this code does a lot of). Thanks for the heads-up on heapq, by the way -- it's new to me and a blimmin' good idea. PS: It's faster to use heapreplace(...) than heappop(...);heappush(...) but it only saves a few %.