Last active
December 23, 2015 22:29
-
-
Save ProProgrammer/6703163 to your computer and use it in GitHub Desktop.
The median is the middle number in a sorted sequence of numbers.Finding the median of [7,12,3,1,6] would first consist of sorting the sequence into [1,3,6,7,12] and then locating the middle value, which would be 6.If you are given a sequence with an even number of elements, you must average the two elements surrounding the middle.For example, th…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Checks if the length of the list is even | |
def len_even(y): | |
if len(y) % 2 == 0: | |
return True | |
else: | |
return False | |
def median(x): | |
y = sorted(x) | |
if not len_even(y): | |
return y[(len(y) / 2)] #returns the rounded down value when len(y) / 2 computed. Eg: if length is 5, it will return 2 not 2.5 | |
else: | |
mid_position1 = y[(len(y) / 2) - 1] | |
mid_position2 = y[(len(y) / 2)] | |
return (mid_position1 + mid_position2) / 2.0 | |
""" | |
Explanation: | |
If length of y is an even number, there is no direct median in such a case we need to add the two numbers surrounding middle position and then divide them by 2 | |
(y[(len(y) / 2) - 1] + y[(len(y) / 2)]) / 2.0 | |
Breaking down the above line with explanations: | |
y[(len(y) / 2) - 1] --> Gives the integer at rounded down position | |
y[(len(y) / 2) --> Gives the next integer in list | |
(y[(len(y) / 2) - 1] + y[(len(y) / 2)]) / 2.0 --> Adds both and divides by 2.0 (not 2) so that the result is a float not integer | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment