Chalarangelo / 30-seconds-of-python

Short Python code snippets for all your development needs
https://www.30secondsofcode.org/python/p/1
Creative Commons Attribution 4.0 International
8.83k stars 1.26k forks source link

Making median code a bit more precise. #367

Closed Navaneethnanda closed 3 years ago

Navaneethnanda commented 3 years ago

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.

Chalarangelo commented 3 years ago

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.