设计输出斐波那契数列的python
时间: 2024-09-24 21:19:05 浏览: 32
fibo.rar_55_fibo_python用递归写斐波那契数列fibo
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_list = fibonacci_recursive(n - 1)
fib_list.append(fib_list[-1] + fib_list[-2])
return fib_list
n_terms = int(input("请输入要输出的项数:"))
print(fibonacci_recursive(n_terms))
```
2. **循环**(效率较高)
```python
def fibonacci_loop(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
next_num = fib_sequence[-1] + fib_sequence[-2]
fib_sequence.append(next_num)
return fib_sequence[:n]
n_terms = int(input("请输入要输出的项数:"))
print(fibonacci_loop(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 = int(input("请输入要输出的项数:"))
fib_gen = fibonacci_generator(n_terms)
print([next(fib_gen) for _ in range(n_terms)])
```
阅读全文