[Python-ideas] Pass a function as the argument "step" of range()
Pierre Quentel
pierre.quentel at gmail.com
Fri Jul 3 13:11:56 CEST 2015
2015-07-03 12:23 GMT+02:00 Chris Angelico <rosuav at gmail.com>:
> 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.
No, that's very easy, just rewrite the function :
previous = 987
def fibo(last):
global previous
_next, previous = previous+last, last
return _next
print(list(Range(1597, 10000, fibo)))
and erase the browser history ;-)
More seriously, you can't produce this sequence without starting by the
first 2 item (0, 1), no matter how you implement it
> 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
> _______________________________________________
> 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/7af28432/attachment.html>
More information about the Python-ideas
mailing list