求斐波那契数列Python代码
时间: 2024-10-25 13:08:10 浏览: 12
当然可以,求斐波那契数列是一个常见的编程练习。在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 = int(input("请输入一个正整数:"))
print(fibonacci_recursive(n))
```
2. **循环**:
```python
def fibonacci_iterative(n):
fib_sequence = [0, 1] if n >= 1 else []
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence[:n]
n = int(input("请输入一个正整数:"))
print(fibonacci_iterative(n))
```
3. **生成器函数** (更高效,因为不会一次性生成整个序列):
```python
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
n = int(input("请输入一个正整数:"))
fib_sequence = list(fibonacci_generator(n))
print(fib_sequence)
```
阅读全文