Range function

Peter Hansen peter at engcorp.com
Sun May 15 09:20:44 EDT 2005


Xah Lee wrote:
> Here's the Python solution.
> # implementation note: When iStep is a decimal, rounding error
> # accumulates. For example, the last item returned from
> # Range(0,18,0.3) is 17.7 not 18. A remedy is to turn iStep into a
> # fraction and do exact arithmetics, and possibly convert the result
> # back to decimal. A lesser workaround is to split the interval as to
> # do multiple smaller range and join them together.

Good lord no!  The correct way is to use an integer count and simply 
multiply it each time by the step, and add that to the range.  No 
accumulation of errors then.  Where did you learn to program?
(Rhetorical question of course, as you haven't, yet.)

> def Range(iMin, iMax=None, iStep=None):
>   if (iMax==None and iStep==None):
>     return Range(1,iMin)
>   if iStep==None:
>     return Range(iMin,iMax,1)
>   if iMin <= iMax and iStep > 0:
>     if (isinstance(iStep,int) or isinstance(iStep,long)):
>       return range( iMix, iMax, iStep)
>     else:
>       result=[];temp=iStep
>       while iMin <= iMax:
>         result.append(iMin)
>         iMin += iStep
>       return result

That's some of the worst Python code I've seen recently.  Please, no one 
take this as representative of how decent Python programmers write code.

-Peter



More information about the Python-list mailing list