Median


#1

Hi
Does anybody can explain and help
I can count and find middle values and etc , but how i can get in this code real result of dividing
def median(data):
count =0
total =0
data.sort()
for x in data:
count +=1
total +=x
print total,count
return total/count

print median([4,5])

return is now 4 but result of 9/2 should be 4.5 ?
How I can return 4.5?


#2

Python 2 uses floor dividing by default, meaning it rounds down if it isn't a whole number. You need to divide by a float for the output to be a float.


#3

I had a similar problem with the following code. I find it useful to 'test' the code in the Python IDLE I installed, version 3.6. And it did work in 3.6, but not on the website.

def median(numbers):
    sorted_n = sorted(numbers)
    half = int (len(sorted_n) / 2)
    if len(sorted_n) % 2 == 1:
        med = sorted_n[half]
    else:
        med = ((sorted_n[half] + sorted_n[half-1]) / 2)
    return med

The solution to make it work on this site was to change to:

def median(numbers):
    sorted_n = sorted(numbers)
    half = int (len(sorted_n) / 2)
    if len(sorted_n) % 2 == 1:
        med = sorted_n[half]
    else:
        med = ((sorted_n[half] + sorted_n[half-1]) / 2.0)
    return med

#4

easiest way is to declare in my code total =0.0 and it works.. I found already another solution for this exercise
My median code is next
def median(value):
sort = sorted(value)
if len(sort) % 2 == 0:
return (sort[len(sort)/2] + sort[len(sort)/2-1])/2.0
else:
return sort[len(sort)/2]


#5

insead of deviding the sum by 2 use 2.0 then the answer will be in float


#6

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