【发布时间】:2018-01-04 20:50:03
【问题描述】:
我正在做一个需要很多小素数很多次的项目。我想创建一个可以永远运行的生成器,但会缓存已经生成的值。到目前为止,这是我的代码。
from itertools import count
def prime_sieve(): # postponed sieve, by Will Ness
for c in (2,3,5,7): # original code David Eppstein,
yield c
sieve = {} # Alex Martelli, ActiveState Recipe 2002
ps = prime_sieve() # a separate base Primes Supply:
p = next(ps) and next(ps) # (3) a Prime to add to dict
q = p*p # (9) its sQuare
for c in count(9,2): # the Candidate
if c in sieve: # c’s a multiple of some base prime
s = sieve.pop(c) # i.e. a composite ; or
elif c < q:
yield c # a prime
continue
else: # (c==q): # or the next base prime’s square:
s=count(q+2*p,2*p) # (9+6, by 6 : 15,21,27,33,...)
p=next(ps) # (5)
q=p*p # (25)
for m in s: # the next multiple
if m not in sieve: # no duplicates
break
sieve[m] = s # original test entry: ideone.com/WFv4f
class cached_primes:
def __init__(self):
self.prime_gen = prime_sieve()
self.done = False
self.vals = []
for value in self._gen_new(0, 3):
pass
def get(self, start=0, end=float('inf')):
vals = self.vals
if start == 0:
lo = 0
else:
lo = bisect_left(vals, start)
if vals[-1] > end:
hi = bisect_right(vals, end, lo=lo)
yield from islice(vals, lo, hi)
return
yield from islice(vals, lo, len(vals))
yield from self._gen_new(start, end)
def _gen_new(self, start, end):
for prime in self.prime_gen:
print(prime)
self.vals.append(prime)
if start <= prime <= end:
yield prime
elif end < prime:
return
此代码的问题在于,如果多个源正在生成新的素数,它们将跳过另一个生成的素数。我该如何解决这个问题?
【问题讨论】:
-
你真的需要重新实现一个素筛和一个缓存吗???
-
如果素数很小,那么小素数的列表也会很小。只需在列表中生成一次并重复使用该列表?
-
我正在尝试编写代码来生成梅森素数的无限生成器,因此虽然素数都相对较小(至少与整个程序中的其他数字相比),但我最终需要任意大的素数.
-
这段代码非常聪明。如此聪明,事实上,我不确定它的作用或工作原理。
-
将缓存共享为类变量而不是实例变量,但始终使用锁访问它。