Assigning probabilities to items in python
<p>I understand the question title is vague. My apologies. I have a hashmap that has the key:value <code>&lt;string&gt;:&lt;list of lists&gt;</code>. For a given list, each of the items in the list has a corresponding probability of being chosen. For example, one item in the hashmap might look like</p>

<pre><code>"NP":[['A', 'B'], ['C', 'D', 'E'], ['F']]
</code></pre>

<p>I need to choose one of the lists on the right hand side randomly. Each list has it's own probability. Here are the input strings that would generate the above item in the map.</p>

<pre><code>3 NP A B
1 NP C D E
1 NP F
</code></pre>

<p>Because the line <code>NP A B</code> has the number <code>3</code> next to it, <code>NP C D E</code> has <code>1</code> next to it, and <code>NP F</code> has <code>1</code> next to it, the probability ratio is 3:1:1, so <code>[A, B]</code> has 3/5 probability of being chosen, <code>[C, D, E]</code> has 1/5 of being chosen and same for <code>[F</code>. </p>

<p>My question is, how do I simulate those probabilities? </p>

<p>Before those numbers were introduced it was easy because I could count the length of the list (in the above example it would be 3) and then choose a random number between 0 and <code>len(list) - 1</code> inclusive with <code>random.randint()</code>, then choose that index from the list. To simulate bernoulli random variables, I know that one can check <code>if random.randint() &lt; p</code>. But that only works if you have 2 cases. I can't explicitly write if statements to check because a list might have <code>n</code> elements. </p>

<p>So the way I would solve this is by creating a sparse table ranging from <code>0</code> to <code>total probability</code>. In your case, that's </p>

<pre><code>0 -&gt; 0
3 -&gt; 1
4 -&gt; 2
</code></pre>

<p>Then pick an int between 0 and 4, and pick the largest value >= the chosen value (in other words, 1 maps to 0, 2 maps to 0, 3 maps to 1). The 'value' in this mapping corresponds to the sublist in your original dictionary. That shouldn't take any additional libraries.</p>

python probability