首页 > 代码库 > python 给定n,返回n以内的斐波那契数列

python 给定n,返回n以内的斐波那契数列

方式一:函数

技术分享
1 def fabs(n):
2     a, b = 0, 1
3     while b < n:
4         print(b, end= )
5         a, b = b, a+b
6 
7 fabs(1000)
View Code

方式二:列表

技术分享
1 result = [0, 1]
2 
3 def fabs(n):
4     while n-result[-1] > result[-2]:
5         result.append(result[-2] + result[-1])
6 
7 fabs(100)
8 print(result)
View Code

方式三:类

技术分享
 1 class Fabs:
 2     
 3     def __init__(self, max):
 4         self.max = max
 5         self.a, self.b = 0, 1
 6 
 7     def __iter__(self):
 8         return self
 9 
10     def next(self):
11         if self.b<self.max:
12             r = self.b
13             self.a, self.b = self.b, self.a+self.b
14             return r
15 
16 
17 f1 = Fabs(1000)
18 m = f1.next()
19 while m:
20     print(m, end= )
21     m = f1.next()
View Code

方式四:生成器

技术分享
1 def fabs(n):
2     a, b = 0, 1
3     while b<n:
4         yield b
5         a, b = b, a+b
6 
7 if __name__ == __main__:
8     for i in fabs(1000):
9         print(i, end= )
View Code

 

python 给定n,返回n以内的斐波那契数列