Median - throwing error


#1



Practice makes perfect: Median

I am unsure what this error message means and where my code is wrong:

"Oops, try again. median([4, 5, 5, 4]) resulted in an error: unsupported operand type(s) for /: 'tuple' and 'int'"


As with everyone else, I expected my code just to run without problems.


def median(numbers):
    new_list = sorted(numbers)
    if (len(numbers) % 2) == 0:
        return (new_list[len(new_list)/2],
        + new_list[(len(new_list)/2) - 1])/2
    else:
        return new_list[(len(new_list)/2) - 1]


#2

(new_list[len(new_list)/2],
        + new_list[(len(new_list)/2) - 1])

Is a tuple and you are dividing it by an integer
(you can rewrite it as:

a = new_list[len(new_list)/2]
b = + new_list[(len(new_list)/2) - 1]
(a, b)  # this is a tuple
(a, b) / 2  # and dividing a tuple by an integer doesn't make sense

#3

Why is the integer output from new_listlen(new_list)/2 not added to the integer from new_list(len(new_list)/2) - 1 ?


#4

Why would it be? Have you used the + operator on them?

[+1, +3, +4]

Those values are not added. Those are three separate values, each its own element in a list.
Positive 1, positive 3, positive 4


#5

The "+" after what I shall refer to as 'a' for ease of reading. Does this not add the integers together?


#6

You did (a, +b)

To add a and b, you would do: a + b


#7

Ahh I had thought the comma allowed the statement to go over multiple lines like an IF statement. I did not understand this properly. Removing the comma and fixing a couple of mistakes gave me the correct answer.

def median(numbers):
    new_list = sorted(numbers)
    if (len(numbers) % 2) == 0:
        return float((new_list[(len(new_list)/2) - 1] + new_list[len(new_list)/2])) / 2
    else:
        return new_list[(len(new_list)/2)]

#8

Usually better to store partial results in variables:

numbers = sorted(numbers)
middle = len(numbers) // 2
last_of_first_half = new_list[middle - 1]
first_of_second_half = new_list[middle]
median = (last_of_first_half + first_of_second_half) / 2.0

That way you can reason about each part being correct without having to consider the rest. That's how you manage complexity, you just split it up and reason about one part at a time, in isolation of the rest.


#9

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