
本文详解修复斐波那契迭代器类中 max_count=0 和 max_count=1 时序列生成错误的问题,通过调整状态更新与返回顺序,确保 list(Fibonacci(n)) 精确生成前 n+1 项(即索引 0 到 n),并通过统一逻辑覆盖所有边界情况。
本文详解修复斐波那契迭代器类中 `max_count=0` 和 `max_count=1` 时序列生成错误的问题,通过调整状态更新与返回顺序,确保 `list(fibonacci(n))` 精确生成前 `n+1` 项(即索引 0 到 n),并通过统一逻辑覆盖所有边界情况。
在实现可迭代的斐波那契生成器时,一个常见陷阱是混淆“生成项数”与“最大索引”的语义。原代码将 max_count 解释为“最多生成 max_count 个数”,但测试用例却期望 Fibonacci(0) 返回 [0]、Fibonacci(1) 返回 [0, 1]——这实际意味着:max_count 表示生成从第 0 项到第 max_count 项(含)的闭区间,共 max_count + 1 个数。
原逻辑的问题在于:
-
__next__中先计算新值再返回,导致首项0被跳过; -
max_count == 0的特殊分支与主逻辑割裂,破坏一致性; - 终止条件
self.current_count >= self.max_count错误地限制为max_count次迭代,而非max_count + 1次。
✅ 正确解法是统一处理所有情况:
- 将终止条件改为
self.current_count > self.max_count(即允许生成0..max_count共max_count+1项); - 在每次
__next__中,先保存当前self.current_number作为返回值,再同步更新current_number和next_number; - 使用解包赋值提升可读性与原子性:
return_value, self.current_number, self.next_number = self.current_number, self.next_number, self.current_number + self.next_number。
以下是修正后的完整实现:
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 # Generates terms F₀ through Fₘₐₓcₒᵤₙₜ (inclusive)
self.current_count = 0 # Counts how many terms have been yielded (starts at 0)
self.current_number = 0 # F₀ = 0
self.next_number = 1 # F₁ = 1
if not isinstance(max_count, int):
raise ValueError(f'{max_count} is not an integer.')
def __iter__(self):
return self
def __next__(self):
# Stop after yielding F_max_count → total count = max_count + 1
if self.current_count > self.max_count:
raise StopIteration
# Capture current value BEFORE updating state
return_value = self.current_number
# Update to next pair: (Fₙ, Fₙ₊₁) → (Fₙ₊₁, Fₙ₊₂)
self.current_number, self.next_number = self.next_number, self.current_number + self.next_number
self.current_count += 1
return return_value? 关键说明:
-
Fibonacci(0)→current_count从 0 开始,0 成立,返回 <code>F₀ = 0,然后current_count变为 1;下次调用因1 > 0触发StopIteration,结果为[0]。 -
Fibonacci(1)→ 第一次返回F₀ = 0(current_count=0),第二次返回F₁ = 1(current_count=1),第三次因2 > 1终止,结果为[0, 1]。 - 该逻辑自然扩展至任意
n:list(Fibonacci(n))总是返回[F₀, F₁, ..., Fₙ](共n+1项)。
⚠️ 注意事项:
- 不要为
max_count == 0单独写分支——它会干扰状态机一致性;统一逻辑更健壮、易维护。 -
isinstance(max_count, int)检查应放在初始化早期,避免后续计算中出现类型错误。 - 若需支持负数
max_count,应在__init__中补充校验(如if max_count )。
通过此重构,所有测试均能通过,且代码具备清晰的数学语义与工业级鲁棒性。

















