Looking for opinion on my code for median


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/median?action=lesson_resume

So here is my code for this exercise and it passes, but I’m just curious for a opinion from a more experienced coder. Is there anything that is redundant? Is there a better or more “natural” way to do this?

Let me know I’m eager to learn this well


def median(x):
  sort_list = sorted(x)
  first = sort_list[len(x) / 2]
  second = sort_list[len(x) / 2 - 1]
  med_even = (first + second) / 2.0
  med_odd = first
  if len(x) % 2 == 0:
    print med_even
    return med_even
  else: 
    print med_odd
    return med_odd

#2

Redundancy and bloat usually go hand in hand. Reducing one reduces the other.

>>> def median(x):
	s = sorted(x)
	n = len(s)
	m = int(n / 2)
	return s[m] if n % 2 else float(s[m - 1] + s[m]) / 2

>>> median([4,5,5,4])
4.5
>>> 

#3

That is a whole lot shorter. I was thinking on doing something like you did by defining less variables beforehand, but my reasoning was it would be more complicated to figure out what was wrong with my code if it didn’t run. (It wouldn’t have turned out as short as yours!)

One question I have about your code here. Why does it not say if n % 2 == 0?
Does python automatically assume that if you don’t specify anything behind n % 2 you want it to be equal to zero?

Thanks for your help


#4

Will be True when n is odd.


#5

Because 1 = True and 0 = False right? I either forgot we learned that in the course so far or it wasn’t in there, but indeed very useful. So just clarifying that here for ppl who might also read this.

Thanks again


#6

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