Median


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/5?curriculum_id=4f89dab3d788890003000096#

Oops, try again. median([4, 5, 5, 4]) returned 5.0 instead of 4.5

I don't know where my code goes wrong. Help.


def median(input_list):
    output_list = sorted(input_list)
    n = len(output_list)
    x = int(n / 2)
    if n % 2 == 0:
        median_even = (output_list[x] + output_list[x+1]) / 2.0
        return median_even
    elif n == 1:
        median_1 = 1
        return median_1
    else:
        median_odd = output_list[x+1]
        return median_odd


#2

Let's assume this is a simple problem, requiring a minimal amount of code. Would the OP code fit this description?

waiting...


#3

It is my mistake about the index!!! Thanks!!!

> def median(input_list):
>     output_list = sorted(input_list)
>     n = len(output_list)
>     x = int(n / 2)
>     if n % 2 == 0:
>         median_even = (output_list[x-1] + output_list[x]) / 2.0
>         return median_even
>     elif n == 1:
>         median_1 = 1
>         return median_1
>     else:
>         median_odd = output_list[x]
>         return median_odd

#4

I'm buying that it works. What I'm not buying is that it is simple. It does not strike me as minimalist code. That's a problem from my my standpoint.

We're to assume our program is being given a list. Our code is written on that assumption.

For the purposes of brevity, let,

u = input_list
output_list = sorted(u)
v = output_list

In other words, don't bloat code. Document it in a way that doesn't. Code is it's own documentation when carefully written and semantic in name choices.

def median(u):
    v = sorted(u)
    w = len(v)
    x = w / 2
    if w % 2: return v[x]
    return float(v[x - 1] + v[x]) / 2

If you are fond of ternaries,

return v[x] if w % 2 else float(v[x - 1] + v[x]) / 2

Version 2.x.x

def median(u):
    v = sorted(u)
    w = len(v)
    x = w / 2
    return v[x] if w % 2 else float(v[x - 1] + v[x]) / 2

Version 3.x.x

def median(u):
    v = sorted(u)
    w = len(v)
    x = int(w / 2)
    return v[x] if w % 2 else (v[x - 1] + v[x]) / 2

#5

Trick is to use the version 2.x.x here and in the labs, and use the 3.x.x. in IDLE and the sandboxes.


#6

Got you. :slight_smile:


#7

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