Python Instance VI

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.