def primes():
"""Generator which yields the sequence of prime numbers via the Sieve of Eratosthenes."""
D = {} # map composite integers to primes witnessing their compositeness
q = 2 # first integer to test for primality
while 1:
if q not in D:
yield q # not marked composite, must be prime
D[q*q] = [q] # first multiple of q not already marked
else:
for p in D[q]: # move each witness to its next multiple
D.setdefault(p+q,[]).append(p)
del D[q] # no longer need D[q], free memory
q += 1
from itertools import islice
list(islice(primes(), 0, 20))
1. 概述
2. for...in 循环的本质
for...in
循环的运行流程for...in
循环的本质 和 iterable 的特点3. 迭代器例一:平方数序列
class
关键字来定义一个类 squares:iter
,然后就可以调用其next()
方法来迭代self.high
的值4. 迭代器例二:斐波那契数列
islice()
方法介绍5. One More Thing...
class
还有__iter__()
__next__()
这样的 “八股” 很啰嗦?6. 练习
6.1 参考答案
Logging
2020-03-30 00:44:30 第一次完整精读完毕 2020-03-21 19:40:30 initialize