median exercise on Codecademy Python course

Posted by | April 23, 2015 | English, Programming, Python | No Comments

I recently wanted to test out my fresh Python skills by doing a Codecademy Python course. I really like the way they explain things and even a complete beginner can start comfortably not just by reading trough pages of documentation, but by seeing examples and putting them to use on their online interpreter. I’ll be doing other courses they have over there for sure, and I highly recommend it, if you’re exploring a new language or are completely new to programming.

During a final exercise called median (under Loops / Practice Makes Perfect) I stumbled upon a first anomaly that I met up until now. The instructions are as follows:

Write a function called median that takes a list as an input and returns the median value of the list.

For example: median([1,1,2]) should return 1.

  1. The list can be of any size and the numbers are not guaranteed to be in any particular order.
  2. If the list contains an even number of elements, your function should return the average of the middle two.

I wrote the function, but line of code that calculated the average of two numbers didn’t quite work:

return (int(sorted_lst[0]) + int(sorted_lst[1])) / 2

So for example if I worked with integers 4 and 5 on this line of code it returned 4, while the result I expected was 4.5. I started to suspect, that this might be a Python 2 way of dividing, because I tested it in Python 3 interpreter that I use on my machine, and it worked flawlessly. Dividing two integers produces a float. A friend of mine confirmed my suspicion. If you divide two integers in Python 2, you get an integer. Actually, now that I think of it it even makes sense. I was just used to doing things in Python 3, and that confused me.

So I played around a bit with division in Python 2:

>>> 9 / 2
>>> float(9) / 2
>>> from __future__ import division
>>> 9 / 2

Python 3 casts an integer to float by default before it divides it, and therefore returns a float. If you don’t need precision you can use floor division, which rounds the result down and returns an integer. For example (Python 3):

>>> 9 / 2
>>> 9 // 2

So this is how my function that passed Codecademy’s checks looked like when I was finished:

def median(lst):
    sorted_lst = sorted(lst)
    if len(lst) % 2 == 0:
        while len(sorted_lst) > 2:
            del sorted_lst[0]
            del sorted_lst[-1]
        return (float(sorted_lst[0]) + float(sorted_lst[1])) / 2
        while len(sorted_lst) > 1:
            del sorted_lst[0]
            del sorted_lst[-1]
        return int(sorted_lst[0])

I know there are differences between the last two major versions of Python, but this was the first time, that I actually had to think a bit harder for what exactly went wrong. Google rocks, and I learned something new today.

Leave a Reply

Your email address will not be published.