A genertor function, which acts as an iterator, provides memory-efficient way to generate a large sequence of data, such as an array with size of 100,000. We have 3 different methods to invoke generators in Python.
In [8]:
def firstn(n):
num = 0
while num < n:
yield num
num += 1
print(sum(firstn(1000000)))
In [10]:
y = (x*2 for x in [1,2,3,4,5])
print y.next()
To implement a iterator, we have to define a class with two specific functions: 1) __iter__ method that returns a iterator (self); 2) next method to generate next instance when the iterator is called in the for loop.
In [3]:
import random
class randomwalker_iter:
def __init__(self):
self.last = 1
self.rand = random.random()
def __iter__(self):
return self
def next(self):
if self.rand < 0.1:
raise StopIteration
else:
while abs(self.rand - self.last) < 0.4:
self.rand = random.random()
self.last = self.rand
return self.rand
rw = randomwalker_iter()
for rw_instance in rw:
print rw_instance