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

前端 未结 6 1895
盖世英雄少女心
盖世英雄少女心 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 06:53

    The algorithm would be this..

    Select a number randomly between 1 and 274. To do that, call a rand() funciton (assume it returns a value between 0 and 1), multiply rand() by 274. The resulting value should now be in a range. If its between 1 and 68, select A, if its between 69 and 130 select B and so on. This way, your probability stays alive and your operation succeeds.

    PS: I am a Java guy, dont know the syntax of Python.

提交回复
热议问题