Median


#1


"Oops try again, your code did not run to end. Check console window for errors." This is the error message.

I was expecting the part of the code I wrote to address arrays containing an even number to return a a sum of the two middle indexes that was then divided by 2.0.

def median(sequence):
    sequence = sorted(sequence)
    if len(sequence) % 2 == 1:
        median = sequence[int(len(sequence)/2)]
        return median
    else: 
        len(sequence) % 2 == 0
        median = sequence[int(len(sequence)/2)] + sequence[int(len(sequence/2)-1)] / 2.0
    return median


#2

elif must have a condition otherwise use else


#3

I changed the "elif" to "else", but there is a new error in line 9 that reads: "Oops, try again. median([4, 5, 5, 4]) resulted in an error: unsupported operand type(s) for /: 'list' and 'int'"


#4

you first want to get the length of the list: len(sequence) and divide that by two, if you have this:

len(sequence/2)

sequence (which contains the list) you are going to divide by two (which is an integer)

Tip, add a function call to see where you go wrong (this code doesn't work, still need the above changes):

def median(sequence):
    sequence = sorted(sequence)
    if len(sequence) % 2 == 1:
        median = sequence[int(len(sequence)/2)]
        return median
    else: 
        len(sequence) % 2 == 0
        median = sequence[int(len(sequence)/2)] + sequence[int(len(sequence/2)-1)] / 2.0
    return median
print median([4,5,5,4])

as the error message tells you:
TypeError: unsupported operand type(s) for /: 'list' and 'int'

you can't divide a list an a integer, you can divide the length of the list by 2


#5

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