Python 分别定义普通函数和递归函数,实现输出斐波那契数列中的前20个数,要求每行输出5个数
时间: 2024-11-04 07:13:35 浏览: 42
在Python中,我们可以分别定义普通函数和递归函数来输出斐波那契数列的前20个数。这里给出两个示例:
**普通函数实现 (循环法)**
```python
def fibonacci_iterative(n):
fib_sequence = [0, 1]
while len(fib_sequence) < n:
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence[:n]
fibonacci_sequence = fibonacci_iterative(20)
for i in range(0, len(fibonacci_sequence), 5):
print(*fibonacci_sequence[i:i+5])
```
**递归函数实现**
```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
fibonacci_sequence = fibonacci_recursive(20)
for i in range(0, len(fibonacci_sequence), 5):
print(*fibonacci_sequence[i:i+5])
阅读全文