【问题标题】:Infinite Caching generator无限缓存生成器
【发布时间】: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

此代码的问题在于,如果多个源正在生成新的素数,它们将跳过另一个生成的素数。我该如何解决这个问题?

【问题讨论】:

  • 你真的需要重新实现一个素筛和一个缓存吗???
  • 如果素数很小,那么小素数的列表也会很小。只需在列表中生成一次并重复使用该列表?
  • 我正在尝试编写代码来生成梅森素数的无限生成器,因此虽然素数都相对较小(至少与整个程序中的其他数字相比),但我最终需要任意大的素数.
  • 这段代码非常聪明。如此聪明,事实上,我不确定它的作用或工作原理。
  • 将缓存共享为类变量而不是实例变量,但始终使用锁访问它。

标签: python generator primes


【解决方案1】:

这就是我想出的方法。不过不是那么干净。

class cached_primes:
    def __init__(self):
        self.prime_gen = prime_sieve()
        self.done = False
        self.vals = [2]
        next(self.prime_gen)

    def get(self, start=2, end=float('inf')):
        vals = self.vals

        lo = bisect(vals, start)
        if vals[-1] >= end:
            hi = bisect(vals, end)
            yield from islice(vals, lo, hi)
            return
        else:
            while vals[-1] < end:
                if len(vals) > lo:
                    bound = len(vals)
                    yield from takewhile(lambda p: p <=end, islice(vals, lo, bound))
                    lo = bound
                vals.append(next(self.prime_gen))
        hi = bisect(vals, end)
        yield from islice(vals, lo, hi)

【讨论】:

    【解决方案2】:

    Python 生成器每个值只生成一次。价值一旦让出,就永远不会再让出。

    这是你的问题:

    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
    

    这将获取从start 到end 的素数从生成器当前所在的位置,而不是从一开始。您正在尝试多次使用来自prime_sieve 的结果,但正如我之前提到的,旧的素数会用尽。这就是为什么它会跳过已经生成的素数。

    您可能会发现next 是一个有用的函数来代替 for 循环。您也可以考虑使用来自itertools 的函数。

    【讨论】:

    • 我只使用了cached_primes 的一个实例,我传递了它。我想要做的是弄清楚某人何时更新了列表,如果有的话就使用这些值。
    • 你在_gen_new 中也有一个错误——这可能是你很多意外行为的根源。我不确定你到底在问什么。
    • 什么是错误?
    • 您正在重用一个可能已经耗尽超出您正在寻找的素数的生成器。我认为您并不真正了解 yield 语句的作用,因此您可能应该在编写更多损坏的代码之前进行研究并弄清楚这一点。
    • 如果你看看我发布的答案,你会发现我有这个
    猜你喜欢
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    相关资源
    最近更新 更多