# if判断
nterms = 10 # 需要显示的数列位数
n1, n2 = 1, 1 # 第一和第二项
count = 3
if nterms <= 0: # 判断输入的值是否合法
print("请输入一个正整数。")
elif nterms == 1:
print("斐波那契数列:")
print(n1)
else:
print("斐波那契数列: ", end='')
print(n1, n2, end=" ")
while count <= nterms:
nth = n1 + n2
print(nth, end=" ")
n1, n2 = n2, nth # # 更新值
count += 1
# 循环
a = 0
b = 1
print('斐波那契数列: ', end='')
while b <= 1000:
print(b, end=' ')
a, b = b, a+b
# yield
def Fibo_Yield_tool(n):
a, b = 0, 1
while n > 0:
yield b
a, b = b, a + b
n -= 1
def Fibo_Yield(n):
# return [f for i, f in enumerate(Fibo_Yield_tool(n))] # 列表解析,这种方式转换速度很慢
return list(Fibo_Yield_tool(n)) # 直接转化为list,这种方式比较快
if __name__ == '__main__':
a = Fibo_Yield(10) # n代表位数
print(a)
# 递归
def Fibo_tool(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return Fibo_tool(n - 1) + Fibo_tool(n - 2)
def Fibo_Recursion(n):
result_list = []
for i in range(1, n + 1): result_list.append(Fibo_tool(i))
return result_list
if __name__ == '__main__':
a = Fibo_Recursion(10) # 代表数列的位数
print(a)