Median


#1

i just wanted to check this : i have solved this problem with these two codes:

1)
def median(number):
number = sorted(number)
length = len(number)
result = ()
if length % 2 == 0:
half = length / 2
first_element = number[half]
second_element = number[(half-1)]
medi = (first_element + second_element)/2.0
result = medi
else:
half_2 = length / 2
mid_eliment = half_2
medi_2 = number[mid_eliment]
result = medi_2
return result
print median([1,1,2])

2)
Replace this line with your code.
def median(list):
list = sorted(list)
if len(list) % 2 == 0:
return (lista[len(list) / 2 ] + lista[(len(list) / 2) - 1])/ 2.0
else:
return lista[len(list) // 2]

i get that essentially both codes are same. however, i just wanted to know which code is better. 1) or 2) . from my limited understanding, id presume that due to the length of the steps in (1) it is likely that execution for (1) will be slower than (2). is that true?


#2

you could measure the execution time?

less lines doesn't mean better code, readability is also an important issue.


#3

This is the most minimal lines of code I used

import numpy

def median(n):
    return numpy.median(n)

#4

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