(Python) algorithm to randomly select a key based on proportionality/weight

前端 未结 6 1843
盖世英雄少女心
盖世英雄少女心 2020-12-09 06:33

I\'m a bit at a loss as to how to find a clean algorithm for doing the following:

Suppose I have a dict k:

>>> k = {\'A\': 68, \'B\': 62, \'         


        
6条回答
  •  抹茶落季
    2020-12-09 07:12

    I've developed an algorithm a few years ago, with application in Perl and SQL, you can read about it here, complete with analysis and tests why it (most likely) is correct.

    The concept is simple: for each item, pick a random number, pull it through some function that depends on the items' weight, and pick the item with the lowest value.

    That function is:

    x[i] = -log(1 - rand())/weight[i]
    

提交回复
热议问题