Skip to content

Instantly share code, notes, and snippets.

@GuillermoPena
Created May 28, 2014 09:02
Show Gist options
  • Save GuillermoPena/8f5865e75d93e27f7b62 to your computer and use it in GitHub Desktop.
Save GuillermoPena/8f5865e75d93e27f7b62 to your computer and use it in GitHub Desktop.
CheckIO - Home Challenge 2 : Median
# CheckIO - Home Challenge 2 : Median
# http://checkio.org
# A median is a numerical value separating the upper half of a sorted array of numbers from the lower half.
# In a list where there are an odd number of entities, the median is the number found in the middle of the array.
# If the array contains an even number of entities, then there is no single middle value,
# instead the median becomes the average of the two numbers found in the middle.
# For this mission, you are given a non-empty array of natural numbers (X).
# With it, you must separate the upper half of the numbers from the lower half and find the median.
def checkio(data):
data.sort() # Sorting list
if (len(data)%2 == 0): # If list length is even
idx=int(len(data)/2)
return (data[idx]+data[idx-1])/2
else: # If list length is odd
return data[len(data)//2]
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list"
assert checkio([3, 1, 2, 5, 3]) == 3, "Not sorted list"
assert checkio([1, 300, 2, 200, 1]) == 2, "It's not an average"
assert checkio([3, 6, 20, 99, 10, 15]) == 12.5, "Even length"
print("Start the long test")
assert checkio(list(range(1000000))) == 499999.5, "Long."
print("The local tests are done.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment