CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/Day16-20/code/example15.py
Views: 729
"""1迭代器 - __iter__ / __next__2itertools - 生成可迭代序列的工具模块3"""4import itertools56from math import sqrt789def is_prime(num):10"""判断素数"""11for factor in range(2, int(sqrt(num)) + 1):12if num % factor == 0:13return False14return True151617class PrimeIter(object):18"""素数迭代器"""1920def __init__(self, min_value, max_value):21assert 2 <= min_value <= max_value22self.min_value = min_value - 123self.max_value = max_value2425def __iter__(self):26return self2728def __next__(self):29self.min_value += 130while self.min_value <= self.max_value:31if is_prime(self.min_value):32return self.min_value33self.min_value += 134raise StopIteration()353637class FibIter(object):38"""斐波那契数迭代器"""3940def __init__(self, num):41self.num = num42self.a, self.b = 0, 143self.idx = 04445def __iter__(self):46return self4748def __next__(self):49if self.idx < self.num:50self.a, self.b = self.b, self.a + self.b51self.idx += 152return self.a53raise StopIteration()545556def main():57# for val in itertools.permutations('ABCD'):58# print(val)59# for val in itertools.combinations('ABCDE', 3):60# print(val)61# for val in itertools.product('黑红梅方', range(1, 14)):62# print(val)63# fib_iter = FibIter(20)64# print('===>', next(fib_iter))65# print('===>', next(fib_iter))66# for val in fib_iter:67# print(val)68prime_iter = PrimeIter(2, 100000)69for val in prime_iter:70print(val)717273if __name__ == '__main__':74main()757677