The python iterator implements the Fibonacci evaluate and the python Fibonacci evaluate
The Fibonacci sequence, also known as the Golden series, is also known as the rabbit Series: F (0) = 0, F (1) = 1, F (n) = F (n-1) + F (n-2) (n ≥ 2, n *). For example, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,144,233,377,610,987,159, 28657,463 ........ this series starts from 3rd items, and each item is equal to the sum of the first two items. When n tends to be infinitely greater, the ratio of the first item to the next item is approaching the golden split ratio by 0.618.
In pythonnext()
An object that calls a function and continuously returns the next value is called an iterator. Use dir (list)
,dir(tuple)
,dir(file)
,dir(dict)
To view the properties of different types of objects._ Iter __Object with this attribute can return to the iterator. The iterator can not only act onfor
Loop, can also benext()
The function is continuously called and the next value is returned until it is finally thrown.StopIteration
An error indicates that the next value cannot be returned.
The following describes how to evaluate Fibonacci using different methods.
1. Simple version
#!/bin/env pythondef fib(n): a, b = 0, 1 for i in range(n): a, b = b, a+b return aprint 'f5', fib(5)print 'f10', fib(10)
Running result
f5 5f10 55
2. Recursive version
#!/bin/env pythondef fib(n): if 0 == n: return 0 elif 1 == n: return 1 else: return fib(n-1) + fib(n-2)print 'f5', fib(5)print 'f10', fib(10)
Running result
f5 5f10 55
3. iterator version
class Fib(): def __init__(self, n): self.a = 0 self.b = 1 self.n = n self.count = 0 def __iter__(self): return self def next(self): res = self.a self.a, self.b = self.b, self.a + self.b if self.count > self.n: raise StopIteration self.count += 1 return resprint 'f5', list(Fib(5))print 'f10', list(Fib(10))
Running result
f5 [0, 1, 1, 2, 3, 5]f10 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
There are still many places to use the iterator, such as reading files.