列出所有的质数 python using generators

本文介绍了一种使用Python生成质数序列的方法,通过定义一个生成器函数实现无限质数序列的生成,同时提供了一种辅助函数用于判断质数,并讨论了不同实现方式。

一般储存一系列数据可以用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值