Median


#1

What is wrong with my code:

def median(sequence):
    sequence.sort
    result=0
    if len(sequence)%2!=0:
        while len(sequence)>1:
            del sequence[0] 
            del sequence[len(sequence)]
        for item in sequence:
            result+=item
        return result
    else:
        while len(sequence)>2:
            del sequence[0] 
            del sequence[len(sequence)]
        for item in sequence:
            result+=item
        result=result/2
        return result

15.median - help please
#2

The above would be written sequence.sort() for an in place sort.

This is an interesting approach, albeit a little verbose and more mechanics than mathematics, but the outcome is feasible. Following is the re-write of three lines...

if len(sequence) % 2:

A non-zero value evaluates to True.

    while len(sequence) > 2:

This ends with a single element in the list, which we can return immediately after the loop.

    return sequence[0]

The final line,

    while len(sequence) > 3:

will end with two elements left in the sequence. The return value will be,

    return float(sum(sequence)) / 2

Refactoring...

def median(sequence):
    sequence.sort()
    n = 3 - len(sequence) % 2
    while len(sequence) > n:
        del sequence[0]
        del sequence[-1]
    return float(sum(sequence)) / 2 if n > 2 else sequence[0]

#3

One would feel better not destroying the original sequence...

def median(sequence):
    s = sorted(sequence)
    n = 3 - len(s) % 2
    while len(s) > n:
        del s[0]
        del s[-1]
    return float(sum(s)) / 2 if n > 2 else s[0]

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.