Range function

Xah Lee xah at xahlee.org
Sun May 15 12:30:19 EDT 2005


the previous posted solutions are badly botched.

Here's a better solution. Any further correction will appear on the
website instead. (http://xahlee.org/tree/tree.html)

Similar change needs to be made for the Perl code... Java code will
come tomorror.

By the way, the code from me are not expected to be exemplary. These
are exercises for all, also as a intro to functional programing to
industry programers. Also, later on there will be non-trivial problems.

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

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

import math;

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( iMin, iMax+1, iStep)
    else:
      result=[]
      for i in range(int(math.floor((iMax-iMin)/iStep))+1):
        result.append( iMin+i*iStep)
      return result
  if iMin >= iMax and iStep < 0:
    if (isinstance(iStep,int) or isinstance(iStep,long)):
      return range( iMin, iMax-1, iStep)
    else:
      result=[]
      for i in range(int(math.floor((iMin-iMax)/-iStep))+1):
        result.append( iMin+i*iStep)
      return result
  # raise error about bad argument. To be added later.

# test
print Range(5,-4,-2)

# Thanks to Peter Hansen for a correction.

 Xah
 xah at xahlee.orghttp://xahlee.org/




More information about the Python-list mailing list