15. median halp ples


#1



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


Oops, try again. median([4, 5, 5, 4]) resulted in an error: list index out of range


def median(numbers):
    result = 0.0
    num_set = sorted(numbers)
    even = 0  
    position = 0
    if len(num_set) % 2 == 0:
        even = num_set[(len(num_set) / 2)]
        result = (even + num_set[(even + 1)]) / 2 
        return result
    else:
        postition = len(num_set) / 2
        result = num_set[position]
        return result


#2

The problem is a result of your if clause. Lets take a look at what we need to do if there is an even amount of numbers. First we need to find the two middle numbers then we have to take the average of those numbers. It looks like that is what you are trying to do with even = num_set[(len(num_set) / 2)].

What that code is doing though, is setting even equal to the value of whatever is occupying that middle place in the list. So when we call median([4, 4, 5, 5]) even will equal 4. This creates a problem when we run the next line because we set result equal to even, which is 4, plus whatever is in the list at the position of even + 1 which equals 5. We only have a list of 4 numbers so it can't grab anything from position 5.

You need to rewrite your code so that you grab from the middle position and then the position one up from that.


#3

Do we need the above line? Answer: No. It is not an accumulator. In both cases in the code where it occurs it is defined with a new assignment.

Three things we need to complete the evaluation:

  1. a sorted sample space (list of data)
  2. a sample size (list length)
  3. a floored middle index

    nums = sorted(numbers)    # check
    n = len(nums)             # check
    m = n // 2                # check
    # or  m = int(n / 2)

Now setting up the return value...

    if n % 2: return nums[m]                  # odd length
    return float(nums[m - 1] + nums[m]) / 2   # even length

The less variables we involve the simpler will be the solution. Part of simplicity comes from not repeating code patterns (caching repeated expression values) and zeroing in on the logic.

Us beginners are often eager to roll up our sleeves and dig right in. Good on us, but we can save a lot of effort by taking a pencil and paper and sketching out our problem. Our first idea is not necessarily the best, but we need to get those ideas on paper.

The OP code is such an example. Once we set out to refine and simplify (reverse engineering, perhaps?) the fog lifts and the code becomes more concise. It comes with practice.


#4

You missed a 4.

median([4,4,5,5])


#5

My apologies for that, I meant median([4,4,5,5]) and was working with those numbers as I wrote my answer so it does not change anything, but I appreciate you pointing that out.


#6

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