Python Exercise Example 6
Title: Number of Fibonacci sequence.
Program Analysis: Fibonacci number (Fibonacci sequence), also known as golden columns, referring to a number of columns: 0,1,1,2,3,5,8,13,21,34, .......
Mathematically, the fee Fibonacci series is a recursive way to define:
F0 = 0 (n=0) F1 = 1 (n=1) Fn = F[n-1]+ F[n-2](n=>2)
Source Code:
method one
#!/usr/bin/python # -*- coding: UTF-8 -*- def fib(n): a,b = 1,1 for i in range(n-1): a,b = b,a+b return a # 输出了第10个斐波那契数列 print fib(10)
Method Two
#!/usr/bin/python # -*- coding: UTF-8 -*- # 使用递归 def fib(n): if n==1 or n==2: return 1 return fib(n-1)+fib(n-2) # 输出了第10个斐波那契数列 print fib(10)
Examples of output above the first 10 Fibonacci number, the result is:
55
Method Three
If you need to output a specified number of Fibonacci number, you can use the following code:
#!/usr/bin/python # -*- coding: UTF-8 -*- def fib(n): if n == 1: return [1] if n == 2: return [1, 1] fibs = [1, 1] for i in range(2, n): fibs.append(fibs[-1] + fibs[-2]) return fibs # 输出前 10 个斐波那契数列 print fib(10)
Run the above program output is:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]