I have FINALLY finished this section of the course, but I can't say that I understand the math of the code I wrote. It works, and most of it makes sense, but I am hung up on how the whole thing works together. Here is my code:
def median(numbers): gah = sorted(numbers) n = len(gah) m = n-1 print gah[n//2] print gah[m//2] return (gah[n//2] + gah[m//2]) / 2.0 print median([7, 12, 3, 1, 6])
Based on the list I'm calling, the
len(gah) should be 5. That makes sense.
Once the numbers are sorted to [1,3,6,7,12], the indices make sense, but I lose the math. For
gah[n//2], we are returning a specific index of the list. If n = 5, and we've divided that by 2, the answer should be 6, as that is the number at index 2. And it is! When I take the same n = 5 and subtract 1, I get m = 4. If I divide that by 2, I will also get 2, and that will also tag 6 for
My question is, how does this math end up providing the mean...? Why do we need to subtract 1 from the length for the second number?? Is this just confusing me because my list is odd, and it would make more sense with an even list? The subtraction of 1 from the length does not make any sense to me. Sigh.