Skip to content

Instantly share code, notes, and snippets.

@akey7
Created October 19, 2018 02:44
Show Gist options
  • Save akey7/fa41a3214847e2464a0a83f6ef53a69a to your computer and use it in GitHub Desktop.
Save akey7/fa41a3214847e2464a0a83f6ef53a69a to your computer and use it in GitHub Desktop.
Find a median in a Pyton list of integers or floats
def median(xs):
"""
When given a standard Python list of numbers, this function will
return the median value. There are a few cases to consider:
1. xs is an empty list: return None
2. A list with one element: returns that element
3. A list with an odd number of elements: Returns the middle value.
4. A list with an even count of elements: Returns the mean of
two points in the middle.
This function is ALLOWED to mutate the list during sorting. It doesn't
need to make a copy first.
Parameters
----------
xs: A standard Python list of float or integer values.
Returns
-------
The median as described above
"""
if len(xs) == 0:
return None
elif len(xs) == 1:
return xs[0]
elif len(xs) % 2 == 1:
xs.sort()
middle_idx = len(xs) // 2
return xs[middle_idx]
else:
xs.sort()
a_idx = len(xs) // 2
b_idx = len(xs) // 2 - 1
return (xs[a_idx] + xs[b_idx]) / 2
if __name__ == '__main__':
print(median([]))
print(median([1]))
print(median([2, 1, 3]))
print(median([2, 1, 7, 7, 7, 3, 3]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment