I am taking an online training course on Python, and am at the following question:
Write a function called median that takes a list as an input and returns the median value of the list. For example: median([1,1,2]) should return 1. The list can be of any size and the numbers are not guaranteed to be in any particular order. If the list contains an even number of elements, your function should return the average of the middle two.
My code seems correct and passes the tests:
def median(thelist):
median = 0
sortedlist = sorted(thelist)
lengthofthelist = len(sortedlist)
centerofthelist = lengthofthelist / 2
if len(sortedlist) == 1:
for value in sortedlist:
median += value
return median
elif len(sortedlist) % 2 == 0:
temp = 0.0
medianparties = []
medianparties = sortedlist[centerofthelist -1 : centerofthelist +1 ]
for value in medianparties:
temp += value
median = temp / 2
return median
else:
medianpart = []
medianpart = [sortedlist[centerofthelist]]
for value in medianpart:
median = value
return median
I am (pretty) sure that, despite passing the tests, the code is neither nice, efficient, nor Pythonic. I am wondering if the community may highlight what I did wrong and how I can improve it.