15: median - Returns 4.0 Instead of 4.5


#1



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


Median of [4, 5, 5, 4] returns error message: "Oops, try again. median([4, 5, 5, 4]) returned 4.0 instead of 4.5."


I searched around and found other user questions with similar issues. I tried fixing it by adding a '.0' to my divisor, but the only thing that did was return the original '4' as a '4.0' instead. I do not know where my code is wrong. Any help would be appreciated.

Note: while looking for the answer elsewhere, I've noticed that my code differs quite considerably from others'. This difference (shown in the code below) may be why my answer is not returning correctly.


def median(hip):
    train = []
    hop = sorted(hip)
    sup = 0
    sap = 0
    if len(hop)%2==0:
        for hit in hop:
            train.append(hit)
        goll = train[0]
        gall = train[len(train)-1]
        while len(train)>2:
            train.remove(goll and gall)
        if len(train)==2:
            for essence in train:
                sap+=essence
            sup+=(sap//2.0)
    else:
        if len(hop)==1:
            for hit in hop:
                sup+=hit
        else:
            while len(hop)>3:
                goll = hop[0]
                gall = hop[len(hop)-1]
                train.append(hit in hop)
                train.remove(goll and gall)
            if len(hop)==3:
                sup==(hop[0]+hop[2])/2
    return sup


#2

I will reserve comment about your code in general. Given all the strange (meaningingless) variable names it just looks like gibberish. No offense intended. It just does not even look like it addresses the median problem.

Python 2 casts a quotient to integer if both numerator and denominator are integers. If one of the operands is a float, the result will be a float. That is why,

n / 2.0

returns a float, even if n is integer. It is however a hack. We should modify types declaratively.

float(n) / 2

It may just be me, but I do not like to see counting numbers arbitrarily converted just to force a desired outcome. If the outcome must be a float, then declare it explicitly, and not on a counting number.

From a standpoint of statistics, a median is the value at the mid-point of a sorted sample space. We do not need a complicated program to determine it, only three key values.

  1. A sorted list of values
  2. The length of the list
  3. The mid-point (middle) of the list

The middle of an odd length list will be a single value at,

middle = int(len(x) / 2)  => x[middle]

The middle of an even length list with be the mean of the middle two values at,

float(x[middle - 1] + x[middle]) / 2

#3

Thanks for the assistance.

However (and I'm just curious here), would it be possible to correctly return the code given the format I used?
For lists with an even length, removing both the first and last terms until only the middle two are left makes logical sense to me. Is there a particular reason why it didn't return the median in the given code?


#4

I am not going to try to analyze your code... It goes way over the top, and as stated earlier, it is gibberish.


#5

Thanks for this. I had completely forgotten how to declare the type of number I wanted returned.


#6

Ok. I got through your code. Hard piece of work.
As mtf said:

Try to give names that make sense and are clear to understand. Of course so that people can easily help you and don't have to put too much time and afford into it, else it will annoy them and you will be stuck without getting help. AND it's not only for us but you also will get confused if your code gets a little longer than just 10-20 lines. So create good habits as long it is easy. But enough with scolding, let's go to your code:

train.remove(goll and gall) You can't nest (is this the right verb?) commands. What your code do is:
evaluate goll and gall -> 6. train.remove(6) so it removes the bigger(?) item in your list (I don't know why;maybe someone else can help eg mtf). So there is only one item removed. What you need is this:

train.remove(goll)
train.remove(gall)

Next: your definition of gol and gal belonges into the while loop; if not and you get a list with 6 items you end up with only remove two of them:

[1,2,3,4,5,6]                ` //please note that this is not real code!`
goll =1
gall=6
while...
    remove goll and gall
[2, 3, 4, 5]

while loop still active but goll and gall are 1 and 6 which are not in your list and can't be removed!

Last but not least:
sup+=(sap//2.0) is incorrect because: assum [4, 5, 5, 4] -> you will be left with [4, 5] -> 9//2=4; 2 goes 4 times in 9 (floor division); What we need here is a normal division: 9/2 will be also 4, but because of integer division 9/2 is 4.5, since we are in python2 you get the integer of 4.5 which is 4 so what we should do float(9)/2 -> 4.5 CORRECT ANSWER! so our code is: sup+=(float(sap)/2); by the way '=' is enough, since sup is 0.

so Our code is working properly.... For even lists!
For the next list ([6, 8, 12, 2, 23]) in the test it fails:

else:
            while len(hop)>3:
                goll = hop[0]
                gall = hop[len(hop)-1]
                train.append(hit in hop)   `// hit is called before it is assigned!`
                train.remove(goll)
                train.remove(gall)
            if len(hop)==3:
                sup==(hop[0]+hop[2])/2

But to be hones I don't what to get into this, too, because I have to re-code the whole loop for this and I fear it will not be the last flaw.

So in general:
Your approach is working but way to complicated. Try to keep it simple. Try another approach.

I hope I could help
Kiluahh


#7

def median(x):
x.sort()
total = 0
for i in range(0,len(x)):
total += x[i]
return (total/len(x))

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

That's all you need to write down instead of all that nonsense (I'm sorry but it's too complicated)


#8

Are you sure you have the correct definition of median? Your code is a mean, not a median.


#9

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