Friday 31 January 2020

What's the difference between iterators and generators in Python?

Iterators and Generators are related in a similar fashion to how a square and rectangle are related.
That is, every generator is an iterator, but not every iterator is a generator.
Iterator in this scenario is the rectangle. Iterators are objects that use a next method to get the next value in a sequence. Say for example you wanted to create an iterator for the Fibonacci sequence. You might write,
  1. class Fib:
  2. def __init__(self, max = None):
  3. self.previous = 0
  4. self.current = 1
  5. def __iter__(self):
  6. return self
  7. def next(self):
  8. self.previous, self.current = self.current, self.previous + self.current
  9. return self.previous

Now we can call the .next() method on an instance of Fib. We have created an iterator. islice() can be used in various ways, such as printing the first 10 terms in the fibonacci sequence.
  1. >>> fibs = Fib()
  2. >>> for i in islice(fibs, 10):
  3. >>> print i,
  4. 1 1 2 3 5 8 13 21 34 55
A generator is a function that uses the yield statement to create an iterable.
  1. def fibGenerator(numTerms):
  2. first = 0
  3. second = 1
  4. for i in xrange(numTerms):
  5. yield first
  6. first,second = second, first + second
We have created a generator. We can use them as follows
  1. >>> fib_sequence = fibGenerator(10)
  2. >>> for i in fib_sequence:
  3. >>> print i,
  4. 0 1 1 2 3 5 8 13 21 34
When you use the xrange() builtin function, you are using an iterable.
So why use generators and iterables?
Well one cause is that its some distance more memory efficient. Lets say you had some big graph and you desired to follow some path and print out every cost alongside your walk. You may want to follow your course and store each fee along the walk, and then on the end you could loop thru the values and show the effects.

No comments:

Post a Comment

wordEmbeddingLayers() available in Deep Learning Toolbox?

Hello,   trying to run the  "Deep Beer Designer" , I got stuck on the use of  wordEmbeddingLayer()  which is flagged as an unknown...