Python Exercise Example 6
Topic:Fibonacci sequence.
Program analysis:The Fibonacci sequence, also known as the golden section sequence, refers to the following sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
In mathematics, the Fibonacci sequence is defined recursively:
F0 = 0 (n=0) F1 = 1 (n=1) Fn = F[n-1]+ F[n-2](n=>2)
Program source code:
Method 1
#!/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
# Output the 10th Fibonacci number
print (fib(10))
Method 2
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Using recursion
def fib(n):
if n==1 or n==2:
return 1
return fib(n-1)+fib(n-2)
# Output the 10th Fibonacci number
print (fib(10))
The above example outputs the 10th Fibonacci number, with the result:
55
Method 3
If you need to output a specified number of Fibonacci numbers, 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
# Output the first 10 Fibonacci numbers
print (fib(10))
The above program outputs the following result:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]Other extensions
Python 100 Examples