類迭代器實現素數(Python)
阿新 • • 發佈:2019-02-17
class MyPrimes: def __init__(self, start, end): self.start = start self.end = end def isPrimes(self, item): if item <= 1: return False for y in range(2, item): if item % y == 0: return False return True def __iter__(self): self.cur_val = self.start return self def __next__(self): for item in range(self.cur_val, self.end): if self.isPrimes(item): self.cur_val = item + 1 return item raise StopIteration print([x for x in MyPrimes(5, 20)])