Median (completed, want critique)

#1

Hey guys. I finished the median challenge, and am looking for your critiques. Any way to possibly make this code better? I know readability isn't very good, but I am wondering if there are other ways to run this code.

``````import math

def median(numbers):
sorted_numbers = sorted(numbers)

if len(sorted_numbers) % 2 == 0:
return (int(math.floor(sorted_numbers[len(sorted_numbers)/2-1])) + int(math.floor(sorted_numbers[len(sorted_numbers)/2]))) / (2.0)
else:
return int(math.floor(sorted_numbers[len(sorted_numbers)/2]))

print median([5,4,3,7,1])``````

#2

there is no need to use math.floor() on the list-items. for example if you list would be [5,4.4,3,7,1] your result would be 4 instead of 4.4

and if you already floored it - no need to cast it to int because it is already an int

you can simply write:

``````import math

def median(numbers):
sorted_numbers = sorted(numbers)
mid_index = len(sorted_numbers) / 2
if len(sorted_numbers) % 2 == 0:
return (sorted_numbers[mid_index-1] + sorted_numbers[mid_index]) / 2.0
else:
return sorted_numbers[mid_index]

print median([5,4,3,7,1])``````

#3

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