[Python-ideas] Pass a function as the argument "step" of range()

Pierre Quentel pierre.quentel at gmail.com
Fri Jul 3 12:17:34 CEST 2015


2015-07-03 11:56 GMT+02:00 Chris Angelico <rosuav at gmail.com>:

> On Fri, Jul 3, 2015 at 5:30 PM, Pierre Quentel <pierre.quentel at gmail.com>
> wrote:
> > With the proposed Range class, here is an implementation of the Fibonacci
> > sequence, limited to 2000 :
> >
> > previous = 0
> > def fibo(last):
> >     global previous
> >     _next, previous = previous+last, last
> >     return _next
> >
> > print(list(Range(1, 2000, fibo)))
>
> Without the proposed Range class, here's an equivalent that doesn't
> use global state:
>
> def fibo(top):
>     a, b = 0, 1
>     while a < 2000:
>         yield a
>         a, b = a + b, a
>
> print(list(fibo(2000)))
>
> I'm not seeing this as an argument for a variable-step range
> func/class, especially since you need to use a global - or to
> construct a dedicated callable whose sole purpose is to maintain one
> integer of state. Generators are extremely expressive and flexible.
>

Of course there are lots of ways to produce the Fibonacci sequence, and
generators are perfect for this purpose. This was intended as an example of
how to use the proposed range() with always the same logic : build a
sequence of integers from a starting point, use a function to build the
next item, and stop when a "stop" value is reached.


> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20150703/6cd411ce/attachment.html>


More information about the Python-ideas mailing list