Hacker News new | ask | show | jobs
by rthomas6 2649 days ago

    reduce(lambda x,y: (x+y)/2.0, numlist)
Why wouldn't this work?
5 comments

Because you're placing a higher weight on elements that come later in the list. Try it for the list [1, 2, 3, 4]

The mean is 2.5 if you sum them all and divide by 4.

With that method it is:

mean([1, 2, 3, 4]) = mean([1.5, 3, 4]) = mean([2.25, 4]) = 3.125

It doesn’t compute the average. Consider this test case: [0,0,0,0,0,0,4]. Your snippet would return an average of 2.
Just work out the math for N = 3 and you'll see why your solution is wrong.

X = Mean([a,b,c]) = (a+b+c)/3

Y = YourFunction([a,b,c]) = (((a+b)/2)+c)/2 = (a+b+2c)/4

X does not equal Y. It doesn't matter if the reduce is left or right, btw, it's still wrong.

What happens to the denominator when you have 3+ elements?
The function is not associative.