Skip to content
Advertisement

Why does “random.choices” return always the same element when passing a list “cum_weights” of decreasing values?

I don’t understand the cum_weights parameter of random.choices.

I read that it is:

Weight of previous element + own weight [10, 5, 1] → [10, 15, 16]

So as I understand it, the probability of "cherry" is 16 and it is the highest. So why is "apple" more repetitive as a result?

import random

mylist = ["apple", "banana", "cherry"]
print(random.choices(mylist, cum_weights=[10, 5, 1], k=9))

outputs:

['apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple']

Advertisement

Answer

When you have relative weights, the cumulative weights look like the sum of those values:

Your cum_weights should be: [10, 15, 16]

mylist = ["apple", "banana", "cherry"]
print(random.choices(mylist, cum_weights=[10, 15, 16], k=14))
['apple', 'banana', 'cherry', 'banana', 'apple', 'banana', 'apple', 'apple', 'banana', 'banana', 'apple', 'banana', 'banana', 'banana']
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement