(toiminnot)

hwechtla-tl: Sieve of erastothenes in clean python

Kierre.png

Mikä on WikiWiki?
nettipäiväkirja
koko wiki (etsi)
viime muutokset


(nettipäiväkirja 17.11.2017) I tried to find a succinct implementation of Erastothenes' sieve using Python generators. I was astounded that it took more time to find a decent one than to write it. So, I'm contributing my version:

from itertools import count

def sieve(nums):
 p = next(nums)
 yield p  
 yield from sieve(n for n in nums if n%p)

def primes(): return sieve(count(2))

The versions here (http://www.macdevcenter.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html?page=2) or here (https://stackoverflow.com/questions/2211990/how-to-implement-an-efficient-infinite-generator-of-prime-numbers-in-python) are IMNSHO much less representative.


kommentoi (viimeksi muutettu 17.11.2017 13:13)