我有一个链表,我在一个范围内迭代并返回可以表示为该范围内的整数的所有平方数。不是只返回可以执行此操作的数字,而是返回中间的 None
,例如 9, None, None...,16, None, None..., 25
我希望它只返回 9、16、25 等
class Squares:
def __init__(self, start, end):
self.__start = start - 1
self.__end = end -1
def __iter__(self):
return SquareIterator(self.__start, self.__end)
class SquareIterator:
def __init__(self, start, end):
self.__current = start
self.__step = 1
self.__end = end
def __next__(self):
if self.__current > self.__end:
raise StopIteration
else:
self.__current += self.__step
x = self.__current - self.__step + 1
self.__current - self.__step + 1
if str(x).isdigit() and math.sqrt(x) % 1 == 0:
return x
最佳答案
您需要使您的 __next__
函数继续循环,直到达到目标值:
def __next__(self):
# We're just going to keep looping. Loop breaking logic is below.
while True:
# out of bounds
if self.__current > self.__end:
raise StopIteration
# We need to get the current value
x = self.__current
# increase the state *after* grabbing it for test
self.__current += self.__step
# Test the value stored above
if math.sqrt(x) % 1 == 0:
return x
您应该存储 x,然后递增的原因是,无论如何您都必须递增,即使您没有完美的平方。
关于python - 交互链表时打印 None 而不是什么也不打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46481501/