Distributing integers using weights? How to calculate?

前端 未结 4 396
鱼传尺愫
鱼传尺愫 2020-12-10 09:03

I need to distribute a value based on some weights. For example, if my weights are 1 and 2, then I would expect the column weighted as 2 to have twice the value as the colum

4条回答
  •  暖寄归人
    2020-12-10 09:50

    Distribute the first share as expected. Now you have a simpler problem, with one fewer participants, and a reduced amount available for distribution. Repeat until there are no more participants.

    >>> def distribute2(available, weights):
    ...     distributed_amounts = []
    ...     total_weights = sum(weights)
    ...     for weight in weights:
    ...         weight = float(weight)
    ...         p = weight / total_weights
    ...         distributed_amount = round(p * available)
    ...         distributed_amounts.append(distributed_amount)
    ...         total_weights -= weight
    ...         available -= distributed_amount
    ...     return distributed_amounts
    ...
    >>> for x in xrange(100):
    ...     d = distribute2(x, (1,2,3))
    ...     if x != sum(d):
    ...         print x, sum(d), d
    ...
    >>>
    

提交回复
热议问题