Magnus Lie Hetland in his Beginning python wrote a code to replicate the range() built-in.
def interval(start, stop=None, step=1):
if stop is None:
start, stop = 0, start
result = []
i = start
while i < stop:
result.append(i)
i += step
return result
I re-wrote it like this.
def interval(*args):
if len(args)<1:
raise TypeError('range expected at least 1 arguments, got 0')
elif len(args)>3 :
raise TypeError('range expected at most 3 arguments, got %d' % len(args))
else:
if len(args)==1:
start = 0
stop = args[0]
step = 1
elif len(args)==2:
start=args[0]
stop=args[1]
step=1
elif len(args)==3:
start=args[0]
stop=args[1]
step=args[2]
result = []
while start < stop:
result.append(start)
start+=step
return result
I know my code is lengthier but don't you people think its easier to grasp/understand than Hetland's code? Different peoples' minds work differently. In my mind the code felt easier to understand cos I come from a C background. My emphasis is on code comprehension.
i = start
is indented one level too far. – Omnifarious Dec 15 '11 at 8:55