列出所有的质数 python using generators

一般储存一系列数据可以用list,但是如果数据量很大的时候这样会很占用内存。因此除了普通的函数以外,还有一种generator的方式。标志语句为yield。
题目要求:
Write a generator, genPrimes, that returns the sequence of prime numbers on successive calls to its next() method: 2, 3, 5, 7, 11, ...
分析:
这里要想如何生成质数。一般若x为质数,则x%p != 0(p为之前所有的质数)
初次写的代码:

def genPrimes():
    primelist = [2,]
    yield 2
    num = 3
    flag = 0
    while True:
        for p in primelist :
            if (num%p) == 0 :
                flag = 1
        if flag == 1 :
            flag = 0
            num += 1
        else :
            yield num
            primelist.append(num)
            num += 1
    

除了这种写在一起的方式,还可以单独写一个函数来判读是否为质数。
这种方法比较便于思考。

# Define a helper function to check if x is a prime.
def is_prime(x, prime_list):
    if x == 2:
        return True
    else: 
        for prev_prime in prime_list:
            if x % prev_prime == 0:
                return False
    return True

def genPrimes():
    prime_list = []
    x = 2
    while True:
        # Check if x is a prime:
        if is_prime(x, prime_list):
            yield x
            prime_list.append(x)
        x += 1

other solution

def genPrimes(): 
    from itertools import count as cnt
    pl = [2]
    return (pl.append(i) or pl[-2] for i in cnt(3,2) if all(i%p for p in pl))

这个以2为单位进行加法,因为质数不可能为偶数。
这里还用到了python内建模块intertools,他提供了几个迭代函数。
count()会创建一个无限的迭代器,只能按Ctrl+C退出。
pl[-2] takes the previous prime from the list pl.(why)

原文地址:https://www.cnblogs.com/litingyu/p/9189076.html