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

Chris Angelico rosuav at gmail.com
Fri Jul 3 12:23:28 CEST 2015


On Fri, Jul 3, 2015 at 8:10 PM, Pierre Quentel <pierre.quentel at gmail.com> wrote:
> 2015-07-03 11:54 GMT+02:00 Peter Otten <__peter__ at web.de>:
>>
>> Pierre Quentel 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)))
>>
>> How would you make
>>
>> print(list(Range(1000, 2000, fibo)))
>>
>> work?
>
>
> I wouldn't, the Fibonacci sequence starts with (0, 1), not with (0, 1000)

The whole numbers start with (0, 1) too (pun intended), but you can
ask for a range that starts part way into that sequence:

>>> list(range(10,20))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

You can create "chunked ranges" by simply migrating your previous
second argument into your new first argument, and picking a new second
argument. Or you can handle an HTTP parameter "?page=4" by multiplying
4 by your chunk size and using that as your start, adding another
chunk and making that your end. While it's fairly easy to ask for
Fibonacci numbers up to 2000, it's rather harder to ask for only the
ones 1000 and greater. Your range *must* start at the very beginning -
a very good place to start, don't get me wrong, but it's a little
restrictive if that's _all_ you can do.

ChrisA


More information about the Python-ideas mailing list