编程语言
首页 > 编程语言> > 2022.04.12-python学习之裴波那契数列

2022.04.12-python学习之裴波那契数列

作者:互联网

 1 # File : exercise_06_fibonacci_number.py
 2 # Datetime : 2022/4/11 0011 23:07
 3 
 4 # 玩玩斐波那契列数 输出第10个数的值
 5 
 6 # 使用递归输出
 7 
 8 def fibonacci_number(num):
 9     if num <= 1:
10         return num
11     return fibonacci_number(num - 1) + fibonacci_number(num - 2)
12 
13 
14 print(fibonacci_number(9))  # 以0开头的 所以第10个数需要-1
15 
16 # 使用for循环输出
17 count = 10  # 数列的元素个数
18 before_num = 0  # 第一个数
19 after_num = 1  # 第二个数
20 result = 0
21 for i in range(1, count):
22     if i <= 1:
23         result = i
24     else:
25         before_num, after_num = after_num, before_num + after_num
26         result = after_num
27 
28 print(result)
29 
30 # 使用while循环输出
31 i = 0
32 count2 = 10  # 数列的元素个数
33 before_num1 = 0  # 第一个数
34 after_num1 = 1  # 第二个数
35 result2=0
36 while i < count - 2:  # 第一个数和第二个数已经定义了,从第三个数开始循环计算
37     before_num1, after_num1 = after_num1, before_num1 + after_num1
38     result2 = after_num1
39     i += 1
40 print(result2)
41 
42 
43 # 输出斐波那契列数列表
44 # 使用for循环输出0到1000之间的斐波那契列数
45 fibonacci1_list2 = []  # 斐波那契列数列表
46 before_nuber = 0  # 第一个数
47 after_number = 1  # 第二个数
48 for i in range(0, 1000):
49     res = 0
50     if i <= 1:
51         res = i
52         fibonacci1_list2.append(res)
53     else:
54         before_nuber, after_number = after_number, before_nuber + after_number
55         res = after_number
56         if res < 1000:
57             fibonacci1_list2.append(res)
58         else:
59             break
60 print(fibonacci1_list2)
61 
62 # 使用while循环输出0到1000之间的斐波那契列数
63 fibonacci1_list3 = [0]
64 a, b = 0, 1
65 while b < 1000:
66     a, b = b, a + b
67     fibonacci1_list3.append(a)
68 print(fibonacci1_list3)

 

标签:输出,12,0011,python,number,num,fibonacci,那契,契列数
来源: https://www.cnblogs.com/gdbd/p/16133325.html