经典程序算法之斐波那契数列

题目:斐波那契数列。

程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。

在数学上,费波那契数列是以递归的方法来定义。

一、直接实现

1 #While循环
2 a,b=0,1
3 while b<=10:
4     print(b)
5     a,b=b,a+b
6 #For循环
7 for i in range(10):
8     print(b)
9     a,b=b,a+b
View Code

二、以函数的方式实现

 

1 def fibonacci(n):
2     a,b=0,1
3     while b<=n:
4         print(b)
5         a,b=b,a+b
6 fibonacci(10)
View Code

三、以面向对象的方案实现

 

四、生成器方式实现

 1 def fibonacci(n):
 2     a,b,count=0,1,0
 3     while True:
 4         if count>n:
 5             return
 6         yield a
 7         a,b=b,a+b
 8         count+=1
 9 f = fibonacci(10)
10 while True:
11     print(next(f))
View Code

猜你喜欢

转载自www.cnblogs.com/wuweierdao/p/12206332.html
今日推荐