osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Problem : Generator


Prahallad Achar <acharbly at gmail.com> writes:
> How to implement reverse generator

A generator generates a sequence of values.

The notion "reverse generator" suggests that you have a sequence
of values and want to produce it in reverse order.
This is not always possible.

Consider:
def natural():
  i = 0
  while True: yield i; i += 1

This generator generates all natural numbers (up to the memory limit).
However, there is no "reverse generator" for the sequence of natural
numbers.

If you have a finate sequence of values, you can turn it into
a list, reverse this list and iterate over it. This will give
you a reverse generator for your sequence of values (though maybe
an inefficient one).