FAQ: Learn Python - Practice Makes Perfect - median

faq

#1

This community-built FAQ covers the "[median](
https://discus…icates/330718

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/median
)" exercise in Codecademy’s lessons on Python.

FAQs for the Codecademy Python exercise median:

Join the Discussion. We Want to Hear From You!

Have a new question or can answer someone else’s? Reply (reply) to an existing thread!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources about Python in general? Go here!

Want to take the conversation in a totally different direction? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account, billing, Pro, or Pro Intensive? Reach out to our support team!

None of the above? Find out where to ask other questions here!


#2

Not seeing your question? It may still have been asked before – try (search) in the top-right of this page. Still can’t find it? Ask it below by hitting the reply button below this post (reply).

Other FAQs

The following are links to additional questions that our community has asked about this exercise:

  • This list will contain other frequently asked questions that aren’t quite as popular as the ones above.
  • Currently there have not been enough questions asked and answered about this exercise to populate this FAQ section.
  • This FAQ is built and maintained by you, the Codecademy community – help yourself and other learners like you by contributing!

#3

2 posts were split to a new topic: PyCharm Gives a Different Result than Codecademy


#4

Hello - Could someone help me out and explain why my code isn’t working? The console says “median([1]) returned 0.0 instead of 1”. I’m not sure why this happening since I’m returning the list when the length of the list is a single digit, not the float for average later on in the function.

Any help is appreciated.

Thanks.

def median(lst):
  lst = []
  avg = float(0)
  sortedlst = sorted(lst)
  middle = len(sortedlst) / 2
  if len(lst) == 1:
    return lst
  
  elif len(lst) > 0:
    return lst[middle]
  if middle % 2 != 0:
    avg = lst[middle] + lst[middle-1] / 2
  return avg

#6

my code is working, but i think its a bug- at the 3rd line from the bottom ,“median_place = (sort_len /2) + 0.5”, ive changed it from (-0.5) to +0.5 cause i got an error for the list [2,6,8,12,23]. when its written like that it means “median_place = (5/2) + 0.5 = 3”. that will result the index for list[3] == 12, instead of list [2] == 8. can someone help me understand why?

i hope i was clear, im not an english native speaker

def median(whatev):
sort = sorted(whatev)
sort_len = len(sort)
if sort_len == 1:
return sort[0]
else:
while sort_len > 1:
if sort_len % 2 == 0:
before_place = (sort_len / 2) -1
before = float(sort[before_place])
after_place = before_place + 1
after = float(sort[after_place])
med_even = float((after + before) / 2)
return med_even
else:
median_place = (sort_len /2) + 0.5
median2 = sort[int(median_place)]
return median2


#8

Today someone told me that they didn’t care what their code looked like, how verbose and repetitive it was, how spaghetti-like it was, as long as it worked. They were confident it did so that ended the discussion. A learning experience was lost. Let’s hope the same is not in store here else I’ll be Oh-and-Two for the day.

One cannot believe this code runs, but if it does, kudos to you for getting such a complex engine moving at all. There is so much code there I don’t know where to begin analyzing.

This is not a mammoth task, and should not take more than a few lines of code to perform.

The median is the middle value of a sorted, odd length list, called a sample. If the sorted sample has an even length then the median is the average of the middle two terms.

There are hints of this in the code, but a whole lot of other stuff that seems to be doing all kinds of things. Forgive us if we appear a bit overwhelmed. Could you simplify and reduce so we are not made so weary?


#9

thank you for your reply. i dont know about simplifying the code, if you have pointers i would love to read about it, but my question refers to the last “else” block -that block refers to the case of an odd length of list, the middle value is the median. lets say the length is 7 - the index of the 4th value it is right? well, originally ive written that part like so:

else:
median_place = (sort_len /2) - 0.5
median2 = sort[int(median_place)]
return median2

as “sort” is the list name for the sorted list, that will give us:

median_place = (7/2) - 0.5 = 3
medien2 = sort[int(3) = index of 3 in the list = the 4th value in a list of 7 values.

but that resulted in an error. only when i changed the first line to:

median_place = (sort_len /2) + 0.5

the code worked fine, but this will give us the index of 4- the fifth value in the list. and that is what i dont understand. can you please help me?


#10

Recall that for an odd length list, there are equal number of elements on either side of the median…

[1][2][3]  [4]  [5][6][7]  => sorted list
            ^
         median == 4

and for even length lists to balance out the same way, we need a pair of elements as the median…

[1][2][3]  [4][5]  [6][7][8]  => sorted list
             ^
           median == float(4 + 5) / 2

One goal of simplification is reduction and ellimination of repetition.

Your first line in the earlier example is an good first step… Cache the length. For simplicity we can use n as our variable (it’s less verbose).

Unfortunately it’s beyond that point that things come off the rails by overcomplicating the problem.

Given a list, we’ll call it, sample, our first step is to sort it, which we cache as a separate list so as not to modify the original order, along with the length.

s = sorted(sample)
n = len(s)

I used simple variable names because their definitions are very clear, and right in the code. We have only to look up and see what values they represent without going into verbose detail.

Finding the middle of the list involves simple integer division…

m = n // 2

Consider a list with length 1. What will m be? Answer, 0. This means we do not have to test if the length is one, just return the value at that index… s[0]. This still does not take an extra step as it fits right into the pattern of any odd length list median.

if n % 2: return s[m]    # read as `if n MOD 2 is non-zero`

So in four lines of simple code we have returned the median for all odd length lists.

The final step will involve only even length lists. Here is where we need to take a careful look at the value of m.

 0  1  2    3  4    5  6  7   => indexes
[1][2][3]  [4][5]  [6][7][8]  
             ^
           median

What is the value of m for the above list?

8 // 2  =>  4

Now look where index 4 is in the above? It is the right side of the middle pair, meaning the other member is to the left of that, meaning m - 1. So,

return float(s[m - 1] + s[m]) / 2