My try at code golfing.
The problem of finding the minimum value of ∑W_i*|X-X_i| reduces to finding the weighted median of a list of x[i] with weights <
short, and does what you'd expect. Not particularly space-efficient.
def f(l,i):
x,y=[],sum(i)
map(x.extend,([m]*n for m,n in zip(l,i)))
return (x[y/2]+x[(y-1)/2])/2.
here's the constant-space version using itertools. it still has to iterate sum(i)/2 times so it won't beat the index-calculating algorithms.
from itertools import *
def f(l,i):
y=sum(i)-1
return sum(islice(
chain(*([m]*n for m,n in zip(l,i))),
y/2,
(y+1)/2+1
))/(y%2+1.)