Code Golf: Shortest code to find a weighted median?

后端 未结 7 615
眼角桃花
眼角桃花 2021-01-03 08:23

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 <

7条回答
  •  旧巷少年郎
    2021-01-03 09:05

    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.)
    

提交回复
热议问题