斐波那契额数列 python代码
时间: 2024-10-15 08:00:18 浏览: 24
斐波那契数列python求解代码
5星 · 资源好评率100%
斐波那契数列是一个经典的数列,其特点是每个数字是前两个数字之和。在Python中,你可以通过递归、循环或者生成器函数的方式来实现这个数列。这里提供几种常见的方法:
**1. 递归方法**
```python
def fibonacci_recursive(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib_sequence = fibonacci_recursive(n - 1)
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence
# 示例
n_terms = 10
print(fibonacci_recursive(n_terms))
```
**2. 循环方法**
```python
def fibonacci_iterative(n):
fib_sequence = [0, 1]
for _ in range(2, n):
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence[:n]
# 示例
n_terms = 10
print(fibonacci_iterative(n_terms))
```
**3. 生成器函数**
```python
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# 示例
n_terms = 10
fib_gen = fibonacci_generator(n_terms)
print(list(fib_gen))
```
阅读全文