Exemple #1
0
def turner():
    """Generate prime numbers very slowly using Euler's sieve.

    >>> p = turner()
    >>> [next(p) for _ in range(10)]
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

    The function is named for David Turner, who developed this implementation
    in a paper in 1975. Due to its simplicity, it has become very popular,
    particularly in Haskell circles where it is usually implemented as some
    variation of::

        primes = sieve [2..]
        sieve (p : xs) = p : sieve [x | x <- xs, x `mod` p > 0]

    This algorithm is sometimes wrongly described as the Sieve of
    Eratosthenes, but it is not, it is a version of Euler's Sieve.

    Although simple, it is extremely slow and inefficient, with
    asymptotic behaviour of O(N**2/(log N)**2) which is worse than
    trial division, and only marginally better than ``primes0``.

    In her paper http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf
    O'Neill calls this the "Sleight on Eratosthenes".
    """
    # See also:
    #   http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
    #   http://en.literateprograms.org/Sieve_of_Eratosthenes_(Haskell)
    #   http://www.haskell.org/haskellwiki/Prime_numbers
    nums = itertools.count(2)
    while True:
        prime = next(nums)
        yield prime
        nums = filter(lambda v, p=prime: (v % p) != 0, nums)
Exemple #2
0
 def test_filter(self):
     self.check_returns_iterator(compat23.filter, None, [1, 2, 3])
     result = compat23.filter(lambda x: x > 100, [1, 2, 101, 102, 3, 103])
     self.assertEqual(list(result), [101, 102, 103])
Exemple #3
0
 def test_filter(self):
     self.check_returns_iterator(compat23.filter, None, [1, 2, 3])
     result = compat23.filter(lambda x: x > 100, [1, 2, 101, 102, 3, 103])
     self.assertEqual(list(result), [101, 102, 103])