Python Iterator for Fibonacci evaluation

Source: Internet
Author: User

The Fibonacci sequence (Fibonacci sequence), also known as the Golden Segment, is called the "Rabbit Sequence": F (0) =0,f (1) =1,f (n) =f (n-1) +f (n-2) (n≥2,n∈n*). For example 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368 ... This sequence starts with the 3rd item, each of which equals the sum of the first two items, and when n tends to infinity, the ratio of the previous item to the latter becomes more and more approximate to the golden ratio of 0.618.

  python中可以被next()函数调用并不断返回下一个值的对象称为迭代器。用dir(list), dir(tuple) , dir(file) dir(dict) to see the properties of different types of objects, you will find that they all have a name of__iter__的特殊方法,对象有了这个属性,就能返回迭代器。迭代器不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值,直到最后抛出StopIteration错误表示无法继续返回下一个值了。

The following is the implementation of Fibonacci evaluation using different methods

1. Simple version

# !/bin/env python def fib (n):     = 0, 1 for in      Range (n):        = B, a+    breturn  a Print ' f5 ',  fib (5)print'F10', fib (10)

Run results

F5 555

2. Recursive version

#!/bin/env pythondeffib (n):if0 = =N:return0elif1 = =N:return1Else:        returnFIB (n-1) + fib (n-2)Print 'f5', FIB (5)Print 'F10', FIB (10)

Run results

F5 555

3. Iterator version

classFib ():def __init__(self, N): SELF.A=0 self.b= 1SELF.N=N Self.count=0def __iter__(self):return SelfdefNext (self): res=self.a self.a, self.b= self.b, SELF.A +self.bifSelf.count >SELF.N:Raisestopiteration Self.count+ = 1returnResPrint 'f5', List (Fib (5))Print 'F10', List (Fib (10))

Run results

F5 [0, 1, 1, 2, 3, 51, 1, 2, 3, 5, 8, 13, 21, 34, 55]

There are many more things to do with iterators, such as reading files and so on.

Python Iterator for Fibonacci evaluation

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.