python - 交互链表时打印 None 而不是什么也不打印

标签 python python-3.x list loops

我有一个链表,我在一个范围内迭代并返回可以表示为该范围内的整数的所有平方数。不是只返回可以执行此操作的数字,而是返回中间的 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/

相关文章:

python - 如何在没有 numpy 的情况下在 jit 装饰器上设置二维数组?

python - 根据列名替换值

python - 在包含 python 字符串的列表中提取列表

java - 如何访问 double 值列表?

python - 关于格式化 DataFrame 以与 matplotlib 一起使用的问题

python - Python:从stdin读取和写入Powershell中的二进制文件

具有产生 NameError 的函数链的 Python exec

python - 是否可以预先计算要在 renpy 中打印的文本的高度?

python - C++ OpenCV 中的快速索引

java - 我什么时候需要创建列表的新实例?