Skip to content

Instantly share code, notes, and snippets.

@marskar
Created March 9, 2020 17:25
Show Gist options
  • Save marskar/98410d410978115bfe0a0c19ac749183 to your computer and use it in GitHub Desktop.
Save marskar/98410d410978115bfe0a0c19ac749183 to your computer and use it in GitHub Desktop.
Calculate the median of a series of numbers
def median(vector):
sorted_vector = sorted(vector)
vector_length = len(vector)
middle = vector_length // 2
if vector_length % 2 != 0:
return sorted_vector[middle]
else:
return (sorted_vector[middle] + sorted_vector[middle - 1]) / 2
    
x = [3, 5, 9, 0, 2]
median(x) # 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment