如何用Python编程实现斐波那契数列?
时间: 2024-12-15 20:23:00 浏览: 24
如何使用Python实现斐波那契数列
在Python中,实现斐波那契数列有多种方法,最简单的是通过循环或递归来生成数列。以下是两种常见的实现方式:
1. **循环实现**:
```python
def fibonacci(n):
if n <= 0:
return []
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_terms = int(input("你想计算多少项斐波那契数?"))
print(fibonacci(n_terms))
```
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_terms = int(input("请输入项数:"))
print(fibonacci_recursive(n_terms)[:n_terms]) # 取前n项防止无限递归
```
阅读全文