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

题目:斐波那契数列。

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

算法设计:

step 1 - START FIB
step 2 - get values of a & b
step 3 - get a value control of loop counter
step 4 - display result & get values of a & b
step 5 - STOP


 

一、直接实现

 

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

 

二、生成器方式(函数递归)

 1 import sys
 2 
 3 def fibonacci(n): # 生成器函数 - 斐波那契
 4     a, b, counter = 0, 1, 0
 5     while True:
 6         if (counter > n): 
 7             return
 8         yield a
 9         a, b = b, a + b
10         counter += 1
11 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成
12 
13 while True:
14     try:
15         print (next(f), end="-")
16     except StopIteration:
17         sys.exit()
View Code

三、函数方式

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

 实例二:

1 def fib(n):
2    result = []
3    a, b = 0, 1
4    while b < n:
5       result.append(b)
6       a, b = b, a + b
7    return result
View Code

 

四、面向对象方式

class Fibobj:
    def __init__(self,n):
        self.n=n
    def fib(self):
        a, b = 0, 1
        for i in range(self.n):
            print(b)
            a, b = b, a+b
f=Fibobj(10)
f.fib()

 

posted @ 2020-01-17 16:34  无为而道  阅读(955)  评论(0)    收藏  举报