如何编辑迭代器,同时给出序列中的最后一个数字?我的意思是,总的来说,不是为了这么简单的序列。使用<而不是==不是一个选项。
class P():
def __init__(self, n0):
self.n = n0
def __iter__(self):
return self
def __next__(self):
if self.n == 1:
raise StopIteration
num = self.n
self.n = self.n // 2 if self.n % 2 == 0 else 3 * self.n + 1
return num
nmax = 1000
PP = P(nmax)
PPP = []
for j in PP:
PPP.append(j)
print(PPP)
电流输出:
[10, 5, 16, 8, 4, 2]
期望输出:
[10, 5, 16, 8, 4, 2, 1]