fibonacci数列的Python表示方法

Fibonacci数列为:0、1、1、2、3、5、8、13、21......

数列第一项为0,第二项为1,从第三项开始,每一项为相邻前两项之和。

用递归的方法来定义:

  • F(0) = 0 
  • F(1) = 1
  • F(n) = F(n-1) + F(n-2) , n>=2

用递归方法实现代码:

[python]  view plain  copy
  1. # python 3.4  
  2. x = int ( input ("输入一个数:") )  
  3. def fibonacci ( n ) :  
  4.     if n == 0 :   
  5.         return 0  
  6.     elif n == 1 :  
  7.         return 1  
  8.     else :  
  9.         return fibonacci( n - 1 ) + fibonacci( n - 2 )  
  10. for i in range ( 0 , x ) :  
  11.     print(fibonacci(i))  

用非递归方法实现代码: 

[python]  view plain  copy
  1. # python 3.4  
  2. x = int ( input ("输入一个数:") )  
  3. a, b = 0, 1  
  4. for i in range(0 , x ):        
  5.     print (a)
  6.     a, b = b, a + b


使用generator实现代码: 

[python]  view plain  copy
  1. # python 3.4  
  2. x = int ( input ("输入一个数:") )  
  3. def fib():
  4.     a, b = 0, 1  
  5.     for i in range(0 , x ):        
  6.         yield a
  7.         a, b = b, a + b
  8. print( list(fib(x) )

使用itertools + generator 实现代码
import itertools as it

num_iterations = int(raw_input('How many? '))
def fib():
    a,b = 0,1
    while True:
        yield a
        b = a+b
        yield b
        a = a+b

for x in it.islice(fib(), num_iterations):
    print x

猜你喜欢

转载自blog.csdn.net/permike/article/details/76186726