CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day16-20/code/example15.py
Views: 729
1
"""
2
迭代器 - __iter__ / __next__
3
itertools - 生成可迭代序列的工具模块
4
"""
5
import itertools
6
7
from math import sqrt
8
9
10
def is_prime(num):
11
"""判断素数"""
12
for factor in range(2, int(sqrt(num)) + 1):
13
if num % factor == 0:
14
return False
15
return True
16
17
18
class PrimeIter(object):
19
"""素数迭代器"""
20
21
def __init__(self, min_value, max_value):
22
assert 2 <= min_value <= max_value
23
self.min_value = min_value - 1
24
self.max_value = max_value
25
26
def __iter__(self):
27
return self
28
29
def __next__(self):
30
self.min_value += 1
31
while self.min_value <= self.max_value:
32
if is_prime(self.min_value):
33
return self.min_value
34
self.min_value += 1
35
raise StopIteration()
36
37
38
class FibIter(object):
39
"""斐波那契数迭代器"""
40
41
def __init__(self, num):
42
self.num = num
43
self.a, self.b = 0, 1
44
self.idx = 0
45
46
def __iter__(self):
47
return self
48
49
def __next__(self):
50
if self.idx < self.num:
51
self.a, self.b = self.b, self.a + self.b
52
self.idx += 1
53
return self.a
54
raise StopIteration()
55
56
57
def main():
58
# for val in itertools.permutations('ABCD'):
59
# print(val)
60
# for val in itertools.combinations('ABCDE', 3):
61
# print(val)
62
# for val in itertools.product('黑红梅方', range(1, 14)):
63
# print(val)
64
# fib_iter = FibIter(20)
65
# print('===>', next(fib_iter))
66
# print('===>', next(fib_iter))
67
# for val in fib_iter:
68
# print(val)
69
prime_iter = PrimeIter(2, 100000)
70
for val in prime_iter:
71
print(val)
72
73
74
if __name__ == '__main__':
75
main()
76
77