HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Thinking in python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
pythonthinkingstackoverflow

Problem

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

Solution

I think your code is more straightforward, but its size is a bit daunting. I actually like the original better. The only real 'trick' it uses is multiple assignment. And while it requires you to think through the different cases of range a bit to realize it works, this isn't something I mind. In fact, with yours, if I were to verify its correctness I'd have to spend just as much time because it has so much more code.

I tend to prefer code that's a bit terse, but elegantly handles all the cases to code that laboriously checks each case and handles that case with case-specific code. And this is in any programming language.

Context

StackExchange Code Review Q#6858, answer score: 3

Revisions (0)

No revisions yet.