随机加权选择

14 python

我有这样的数据:

d = (
  (701, 1, 0.2),
  (701, 2, 0.3),
  (701, 3, 0.5),
  (702, 1, 0.2),
  (702, 2, 0.3),
  (703, 3, 0.5)
)
Run Code Online (Sandbox Code Playgroud)

其中(701,1,0.2)=(id1,id2,priority)

如果我知道id1,使用优先级,有没有一种选择id2的漂亮方法?

Func(701)应该返回:
  1 - 在20%的情况下
  2 - 30%
  3 - 50%

百分比当然很粗糙

Phi*_*l H 6

为每个ID1生成累积分布函数,从而:

cdfs = defaultdict()
for id1,id2,val in d:
    prevtotal = cdfs[id1][-1][0]
    newtotal = prevtotal + val
    cdfs[id1].append( (newtotal,id2) )
Run Code Online (Sandbox Code Playgroud)

所以你会有

cdfs = { 701 : [ (0.2,1), (0.5,2), (1.0,3) ], 
         702 : [ (0.2,1), (0.5,2) ],
         703 : [ (0.5,3) ] }
Run Code Online (Sandbox Code Playgroud)

然后生成一个随机数并在列表中搜索它.

def func(id1):
    max = cdfs[id1][-1][0]
    rand = random.random()*max
    for upper,id2 in cdfs[id1]:
        if upper>rand:
            return id2
    return None
Run Code Online (Sandbox Code Playgroud)