For Programmers: Free Programming Magazines  


Home > Archive > Scheme > May 2005 > Re: Range function









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Range function
Xah Lee

2005-05-15, 8:57 am

Here's the Python solution.

----------
# -*- coding: utf-8 -*-
# Python

# http://xahlee.org/tree/tree.html
# Xah Lee, 2005-05

# 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.

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

# test
print Range(0, 18, 0.3)

Peter Hansen

2005-05-15, 3:58 pm

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
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com