You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

斐波那契序列生成类迭代逻辑问题修复求助

斐波那契序列生成类迭代逻辑问题修复求助

看起来问题出在你的__next__方法没有正确返回初始的0值,而且max_count的迭代逻辑和测试期望不匹配。让我帮你分析并修复:

问题根源

  1. 你的__next__方法第一次调用时直接返回了next_number的初始值1,完全跳过了初始的current_number(0),导致max_count=1时只返回[1]。
  2. max_count=0的特殊处理和整体迭代逻辑割裂,使得max_count的含义模糊(max_count=0时迭代1次,其他值按max_count次数迭代)。

修复后的代码

调整__next__的执行顺序,先返回当前斐波那契数再更新后续值,同时统一逻辑让max_count的含义匹配你的测试期望(即max_count=N时生成N+1个元素,对应从0开始的前N+1项斐波那契数):

class Fibonacci:
    """An iterable for creating a Fibonacci series"""

    def __init__(self, max_count):
        """
        Constructor requires a single positional argument
        which must be an integer.
        """

        self.max_count = max_count  # 控制生成的斐波那契数个数:最终生成max_count+1个(适配你的测试用例)
        self.current_count = 0  # 已生成的斐波那契数计数
        self.a = 0  # 当前斐波那契数
        self.b = 1  # 下一个斐波那契数

        # 对非整数输入抛出ValueError
        if not isinstance(max_count, int):
            raise ValueError(f'{max_count} is not an integer.')

        # 可选:禁止负数输入
        if max_count < 0:
            raise ValueError(f'{max_count} cannot be a negative integer.')

    def __iter__(self):
        """返回Fibonacci类实例作为迭代器"""
        return self

    def __next__(self):
        """定义迭代器的迭代逻辑"""
        # 计算需要生成的总元素数:max_count=0时生成1个,其他情况生成max_count+1个
        total_elements = self.max_count + 1 if self.max_count != 0 else 1

        # 达到生成数量上限时停止迭代
        if self.current_count >= total_elements:
            raise StopIteration

        # 先保存当前要返回的斐波那契数
        result = self.a
        # 更新下一组斐波那契数值
        self.a, self.b = self.b, self.a + self.b
        self.current_count += 1
        return result

测试验证

现在运行你的测试用例:

  • test_non_integer:依然正常触发ValueError,通过。
  • test_max_count_0list(Fibonacci(0))返回[0],通过。
  • test_max_count_1list(Fibonacci(1))返回[0, 1],完全匹配测试期望,通过。

可选调整(更合理的逻辑)

如果觉得max_count的含义不够直观,更推荐把max_count定义为要生成的斐波那契数的个数,此时需要修改你的测试用例:

def test_max_count_1():
    """
    Tests that [0] is returned with constructor value of 1
    if cast as a list.
    """
    assert list(Fibonacci(1)) == [0]

def test_max_count_2():
    """
    Tests that [0,1] is returned with constructor value of 2
    if cast as a list.
    """
    assert list(Fibonacci(2)) == [0,1]

对应的代码只需要把total_elements改为self.max_count,并移除max_count=0的特殊处理(如果希望max_count=0返回空列表的话),这样逻辑更清晰。

备注:内容来源于stack exchange,提问作者JSO

火山引擎 最新活动