用循环和递归分别实现斐波那契数列
# 1\ 用for循环实现斐波那契数列
res = []
for i in range(10):
if i < 2:
res.append(1)
else:
res.append(res[i - 1] + res[i - 2])
print(res) # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
# 2、函数递归配合for 实现斐波那契数列
def fib(n):
if n<2:
return 1
else:
return fib(n-1) + fib(n-2)
res = []
for i in range(10):
res.append(fib(i))
print(res) # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
# 3\函数配合列表生成式实现斐波那契数列
def fib(n):
if n<2:
return 1
else:
return fib(n-1) + fib(n-2)
res =[fib(i) for i in range(10)]
print(res) # # [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]