写出python计算斐波拉契数列
时间: 2024-12-29 15:30:36 浏览: 8
Python计算斐波那契数列通常可以使用循环、递归或者生成器等方法。这里提供三种常见的实现方式:
1. **循环法**:
```python
def fibonacci(n):
if n <= 0:
return "输入值应大于0"
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib_sequence = [0, 1]
for i in range(2, n):
fib_sequence.append(fib_sequence[i - 1] + fib_sequence[i - 2])
return fib_sequence[:n]
# 调用函数并打印前几个数字
print(fibonacci(10))
```
2. **递归法**:
```python
def fibonacci_recursive(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
sequence = fibonacci_recursive(n - 1)
sequence.append(sequence[-1] + sequence[-2])
return sequence
# 由于递归可能会造成效率低下的栈溢出问题,对于大的n,推荐使用循环法
print(fibonacci_recursive(10)) # 注意这里的n值不宜过大
```
3. **生成器法**(更高效,节省内存):
```python
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
fib_gen = fibonacci_generator(10)
for num in fib_gen:
print(num)
```
阅读全文