Chalarangelo/30-seconds-of-python

Making median code a bit more precise.

Navaneethnanda opened this issue · 1 comments

The current code of median.md where we have 2 returns it works well.

def median(list):
  list.sort()
  list_length = len(list)
  if list_length % 2 == 0:
    return (list[int(list_length / 2) - 1] + list[int(list_length / 2)]) / 2
  return float(list[int(list_length / 2)])

But by using the below code we get an impression of something close to a formula and it works in the same way the above code works. Also viewers get involved in understanding something basic.

import math
def median(list):
  if not list:
    return -1
  list.sort()
  list_length = len(list)
  half_length=list_length/2
  return (list[int(half_length) - (int(half_length)-math.ceil(half_length)+1)] + list[int(half_length)]) / 2

Thank you and let me know your opinion.

Thanks, but this has been brought up before. While it might be more mathematically correct as a formula, it sacrifices readability in this form, which is why we opted to keep the current implementation.