Median - Is my code unnecessarily complex?


def median(lst):

	new_lst = sorted(lst[:])
	if len(lst) % 2 == 0:
		while len(new_lst) > 2:
		return ((new_lst[0] + new_lst[1]) / 2.0)
		while len(new_lst) > 1:
		return new_lst[0]



Looks good to me, if it works it works.

I do like how you did it though, but yea you waste some CPU cycles doing unnecessary things. It will only matter when you start to work on huge data sets so don't worry about it.

Also here is a fancy sample,

def median(lst):
    return sorted(lst)[len(lst) / 2] if len(lst) / 2 == 1\ # Line break
       else float(sorted(lst)[len(lst) / 2] + sorted(lst)[len(lst) / 2-1]) / 2

As you can see you can make it shorter but not necessarily easier to understand. There are other one liners too but that will come with practice.


Thanks. I'm trying to do each exercise how I first think of it and then see how others approached it in the Q&A. I felt like mine was wasteful.