title: Fibonacci sequence.
Program Analysis: This sequence starts with the 3rd item, each of which equals the sum of the first two. So
N=1,2,f=1
N>2,f=f (n-1) +f (n-2)
For example: 1,1,2,3,5,8 .....
>>> def f6 (n): If N==1 or N==2:return 1elif n>2:return f6 (n-1) +f6 (n-2) else:print ' please input an incorrect num ber
>>> for I in range (1,10):p rint f6 (i) 112358132134>>> f6 ( -2) Please input an incorrect number
Online answers:
Method One
#!/usr/bin/python#-*-Coding:utf-8-*-DefFib(N):a,b = 1,1for i in range(n-1):A ,b = b,a+breturn a# outputs the 10th Fibonacci sequence print fib( ten)
Method Two
#!/usr/bin/python#-*-Coding:utf-8-*-# using recursionDefHi(N):if N==1or N==2: return 1return Fib (n- 1) +fib (n -2) # output the 10th Fibonacci sequence Span class= "PLN" >print Fib (10 /span>
The above example outputs a 10th Fibonacci sequence with the result:
55
Method Three
If you need to output a specified number of Fibonacci sequences, you can use the following code:
#!/usr/bin/python#-*-Coding:utf-8-*-DefFib(N): IfN== 1: Return [1] IfN== 2: Return [1, 1]Fibs= [1, 1] for I in Range (2 N): Fibs. (fibs[-1] + Fibs[-2 ]) return Fibs# output first 10 Fibonacci sequences print Fib (10 /span>
The above program run output is:
[1,1,2,3,5,8,a, A, "
Python Instance VI