[Python-ideas] Pass a function as the argument "step" of range()
Chris Angelico
rosuav at gmail.com
Fri Jul 3 11:56:03 CEST 2015
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.
ChrisA
More information about the Python-ideas
mailing list