编写一个输出斐波那契数列第x项的函数fib(x),分别用递归和非递归的方式实现,并输出向右靠齐的前20项,且每10项换行
时间: 2023-11-22 14:54:12 浏览: 156
递归实现:
```python
def fib(x):
if x <= 1:
return x
else:
return fib(x-1) + fib(x-2)
# 输出前20项斐波那契数列
for i in range(20):
print("%10d" % fib(i), end="")
if (i+1) % 10 == 0:
print()
```
非递归实现:
```python
def fib(x):
if x <= 1:
return x
else:
a, b = 0, 1
for i in range(2, x+1):
c = a + b
a, b = b, c
return b
# 输出前20项斐波那契数列
for i in range(20):
print("%10d" % fib(i), end="")
if (i+1) % 10 == 0:
print()
```
相关问题
我是说编写一个输出斐波那契数列第x项的函数fib(x),分别用递归和非递归的方式实现,并输出向右靠齐的前20项,且每10项换行这个的代码和测试用例
以下是使用递归和非递归方式实现斐波那契数列第x项的代码,并输出向右靠齐的前20项,每10项换行:
```python
def fib_recursive(x):
if x == 1 or x == 2:
return 1
else:
return fib_recursive(x-1) + fib_recursive(x-2)
def fib_iterative(x):
if x == 1 or x == 2:
return 1
else:
a, b = 1, 1
for i in range(3, x+1):
c = a + b
a, b = b, c
return b
for i in range(1, 21):
print("{:>10}".format(fib_recursive(i)), end="")
if i % 10 == 0:
print()
print()
for i in range(1, 21):
print("{:>10}".format(fib_iterative(i)), end="")
if i % 10 == 0:
print()
```
测试用例:
```python
assert(fib_recursive(1) == 1)
assert(fib_recursive(2) == 1)
assert(fib_recursive(3) == 2)
assert(fib_recursive(4) == 3)
assert(fib_recursive(5) == 5)
assert(fib_recursive(6) == 8)
assert(fib_recursive(7) == 13)
assert(fib_recursive(8) == 21)
assert(fib_recursive(9) == 34)
assert(fib_recursive(10) == 55)
assert(fib_iterative(1) == 1)
assert(fib_iterative(2) == 1)
assert(fib_iterative(3) == 2)
assert(fib_iterative(4) == 3)
assert(fib_iterative(5) == 5)
assert(fib_iterative(6) == 8)
assert(fib_iterative(7) == 13)
assert(fib_iterative(8) == 21)
assert(fib_iterative(9) == 34)
assert(fib_iterative(10) == 55)
```
输出结果如下:
```
1 1 2 3 5 8 13 21 34 55
89 144 233 377 610 987 1597 2584 4181 6765
1 1 2 3 5 8 13 21 34 55
89 144 233 377 610 987 1597 2584 4181 6765
```
定义一个求Fibonacci(斐波那契)数列的函数fib(n),并编写测试代码,输出前20项(每项宽度5个字符位置,右对齐),每行输出10个,分别用递归和非递归的方式实现,用python语言
# 递归方式实现Fibonacci数列
def fib_recursive(n):
if n <= 1:
return n
else:
return fib_recursive(n-1) + fib_recursive(n-2)
# 非递归方式实现Fibonacci数列
def fib(n):
if n <= 1:
return n
else:
a, b = 0, 1
for i in range(n-1):
a, b = b, a + b
return b
# 输出前20项Fibonacci数列
for i in range(20):
if i % 10 == 0:
print()
print("{:>5}".format(fib_recursive(i)), end="")
print("\n")
for i in range(20):
if i % 10 == 0:
print()
print("{:>5}".format(fib(i)), end="")
阅读全文