轉自 : 廖雪峰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 ndef _not_divisible(n): return lambda x: x % n > 0def 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新聞熱點
疑難解答