15. 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 instead of 4.5
wone = 4
and
wtwo = 5
add them 9 and divide that by 2 is 4.5 NOT 5


def median(word):
    wordsrt = sorted(word)
    wordlen = len(wordsrt)
    if(wordlen == 1):
        return 1
    if(wordlen % 2 == 0):
        wone = wordsrt[wordlen/2]
        wtwo = wordsrt[wordlen/2+1]
        total = wone+wtwo
        return total/2
    if(wordlen % 2 == 1):
        return wordsrt[wordlen/2]


#2

this:

wone = 4
and
wtwo = 5

are you certain about this? so after we sorted our list we have:

[4,5,5,4]

so the indexes are: 0, 1, 2 and 3. the length is 4, wone:

wone = wordsrt[wordlen/2]
wordsrt[4/2] = 5

then wtwo:

wtwo = wordsrt[wordlen/2+1]
wordsrt[4/2 +1] = 5


#3

problem 2:

after you fixed your indexes, you still have a problem:

(4 + 5) / 2

dividing two integers will give you a integer as result, if needs be, the number is floored. So you will need to do something with float


#4

A post was split to a new topic: 15. median


#5

You can also skip the first and the last conditional. So after you sort your list you start with:
if len(wordsrt)%2 == 0:
#dostuff
else:


#6

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