Files
code/fibonacci.py
芊荨 d6a34e8847 添加斐波那契数列迭代实现
- 新增 fibonacci.py 文件
- 实现 fibonacci(n) 函数,使用迭代方式计算第 n 个斐波那契数
- 包含基本测试用例
2026-04-02 14:40:44 +08:00

38 lines
818 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
def fibonacci(n: int) -> int:
"""
使用迭代方式计算第 n 个斐波那契数
Args:
n: 要计算的斐波那契数的位置(从 0 开始)
Returns:
第 n 个斐波那契数
"""
if n < 0:
raise ValueError("n 必须是非负整数")
if n == 0:
return 0
if n == 1:
return 1
prev, curr = 0, 1
for _ in range(2, n + 1):
prev, curr = curr, prev + curr
return curr
if __name__ == "__main__":
# 测试代码
print("斐波那契数列测试:")
for i in range(10):
print(f"F({i}) = {fibonacci(i)}")
# 验证结果
expected = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
for i in range(10):
assert fibonacci(i) == expected[i], f"测试失败F({i})"
print("\n所有测试通过!")