[Tutor] Getting range to produce float lists

Kirby Urner urnerk@qwest.net
Sat, 20 Apr 2002 00:39:11 -0400


On Wednesday 17 April 2002 06:23 pm, William Griffin wrote:

> I would like to do this by doing range(0, 0.5, 0.1) but of course range
> only produces integer lists and will round all the arguments (making the
> step = 0 if required). Is there a way to do this easily with core
> Python or should I hack up a quick function for my students to use?

Maybe your students'd like to do a quick hack.  One option is 
to pass a,b,d where d = denominator, a,b are regular range 
arguments. 

 >>> from __future__ import division  # to get floating point answers

 >>> def frange(a,b,d):
         return [i/d for i in range(a,b)]

 >>> frange(1,5,10)
 [0.10000000000000001, 0.20000000000000001, 0.29999999999999999,  
 0.40000000000000002]

Could have optional 3rd skip value, and a default denominator of 1,
e.g. frange(a,b,d=1,skip=1) -- stuff like that.  Make it be a 
generator function too if you wanna be fancy.

Another option is to think of a,b as integers and f as a function.

 >>> def frange(a,b,f):
         return [f(i) for i in range(a,b)]

Then you could define f independently as in:

 >>> def f(x):  return x/100.0

Anyway, it's a fun little challenge to help with learning Python.

Kirby



Kirby