delay and force in Python

Benji York benji at benjiyork.com
Wed Jan 19 08:51:01 EST 2005


Will Stuyvesant wrote:
> Streams are interesting because they are to lists like
> xrange is to range.  Could save a lot on memory and
> computations.

I think you're looking for generators.

> Below is my straight translation from Scheme code in the
> Wizard book to Python.

> Something else: this crashes with a "maximum recursion reached"
> . print stream_enumerate_interval(1,998)

Unlike Scheme, Python isn't designed for heavily recursive algorithms. 
Here's a more Pythonic equivalent of your code:

def count(start, stop):
     i = start
     while i < stop:
         yield i
         i += 1

def even(gen):
     for x in gen:
         if x % 2 == 0:
             yield x

numbers = even(count(1, 999))
first = numbers.next()
second = numbers.next()

print second
--
Benji York
benji at benjiyork.com




More information about the Python-list mailing list