python生成素数的程序

    xiaoxiao2021-03-26  23

    转自 : 廖雪峰python教程

    **这段程序使用了filter过滤器对素数进行筛选,令人惊讶的是用于筛选的序列是一个惰性序列** #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 4 21:01:44 2017 @author: jyhkylin """ def _odd_iter(): n = 1 while True: n = n + 2 yield n def _not_divisible(n): return lambda x: x % n > 0 def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列 for n in primes(): if n < 1000: print(n) else: break
    转载请注明原文地址: https://ju.6miu.com/read-658945.html

    最新回复(0)