15/15 median - a solution without conditional "if" statements


#1

def median (l):  
    x = int(round(len(l)/2.0 - 0.1))
    y = int(round(len(l)/2.0 - 0.6))
    return (sorted(l)[x] + sorted (l)[y]) / 2.0

This is my code, which doesn't use any conditionals to evaluate whether there is an odd or even number of items in the list.


#2

Hi @dataninja62392 ,

You can simplify the computation of the middle index(es) by using integer division.

Sort the list, assigning the new list to sl ...

    sl = sorted(l)

Compute the middle index(es) ...

    # a middle index
    i = (len(sl) - 1) // 2
    # a middle index; if len(sl) is odd, then i == j
    j = len(sl) // 2

Compute and return the result ...

   return (sl[i] + sl[j]) / 2.0

#3

what is that 0.6 ?? Is that a formala ??


#4

Yes. that simplifies things a little
I kept trying to divide by 2 first and got boxed into that thread


#5

The logic here is to disregard whether or not there are odd or even number of items and to simply calculate what the 2 middle index(es) are. Actually that statement is not entirely true either because it does make use of the properties of odd and even numbers (when dived by 2) in order to decide what the 2 middle index(es) are. The use of 0.6 and 0.1 is just part of that logic.

It's not the most intuitive way of doing this but the logic just popped in my head and I wanted to try.
appylpye has a cleaner way of doing what is essentially the same thing (https://discuss.codecademy.com/t/15-15-median-a-solution-without-conditional-if-statements/73378/2?u=dataninja62392)


#6

Below is one more solution.

First, a caution is in order. The following two lines are excerpted from PEP 20 - The Zen of Python:

Explicit is better than implicit.
Simple is better than complex.

In that spirit, it is important to write code that is clear to other programmers, whenever that is practical, when that code is aimed at performing real work. However, that does not mean that we cannot write code that performs tricks, as puzzles or for recreational purposes, as we are doing in this thread.

Now with that having been noted, here is a median function that performs the calculation in one line ...

def median(seq):
    return sum(sorted(seq)[(len(seq) - 1) // 2: len(seq) // 2 + 1]) / float((len(seq) + 1) % 2 + 1)

The above is rather abstruse, so we must not code like that when we are doing actual work.

EDITED (below) on January 25, 2017 to apply the float function to the main numerator instead of to the main denominator and to simplify the main denominator ...

def median(seq):
    return float(sum(sorted(seq)[(len(seq) - 1) // 2: len(seq) // 2 + 1])) / (2 - len(seq) % 2)

#7

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