I've been messing with the median problem for a while and couldn't get the lines correct in the case that the number of indexes in the list is even. So I was playing around and changed the variable right_value to be the following.
right_value = ordered list[(len(ordered_list)/2)-1] <-- it's the -1 at the end that confuses me. (See code below for the whole loop.)
It is correct, but I can't really wrap my head around why. By "right value" I am defining it as the index to the right of center in an even array, which will be added to the value left of center and then these two will be divided to get the median. It's the -1 that confuses me. Can anyone help explain why subtracting one index from the right value is correct? Am I simply mislabeling the right and left sides?
I'd really appreciate some clarification!
def median(list): median_value = 0 ordered_list = sorted(list) print ordered_list # median value = middle number in list if len(ordered_list) % 2.0 == 0: left_value = ordered_list[len(ordered_list)/2] print left_value right_value = ordered_list[(len(ordered_list)/2)-1] print right_value median_value += (right_value + left_value)/2.0 return median_value print median_value else: median_value += ordered_list[len(ordered_list)/2] return median_value print median_value