自定义一个实现迭代生成小于某个整数的所有素数的选代器。

class MyIterator:

    def __init__(self, xmax ,x=2):
        self.x = x
        self.xmax = xmax

    def __iter__(self):
        return self

    def panduan(self, item):
        if item <= 1:
            return False
        for i in range(2, item):
            if item % i == 0:
                return False
        return True

    def __next__(self):
        for item in range(self.x, self.xmax):
            if self.panduan(item):
                self.x = item + 1
                return item
        raise StopIteration

if __name__ == '__main__':
    a = int(input('请输入一个大于2的整数:'))
    iter = MyIterator(a)
    print('小于这个整数的素数有:')
    for i in iter:
        print(i)

猜你喜欢

转载自www.cnblogs.com/zhsv/p/12693008.html