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

Posted by LaundroMat on Stack Overflow See other posts from Stack Overflow or by LaundroMat
Published on 2010-04-03T08:41:26Z Indexed on 2010/04/03 8:43 UTC
Read the original article Hit count: 210

Filed under:

Hi -

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, 'C': 47, 'D': 16, 'E': 81}

I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) amount of keys.

>>> sum(k.values()) 
>>> 274

So that there's a

>>> 68.0/274.0
>>> 0.24817518248175183

24.81% percent change that A is selected.

How would you write an algorithm that takes care of this? In other words, that makes sure that on 10.000 random picks, A will be selected 2.481 times?

© Stack Overflow or respective owner

Related posts about python