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?
JavaScript
x
5
1
import random
2
3
mylist = ["apple", "banana", "cherry"]
4
print(random.choices(mylist, cum_weights=[10, 5, 1], k=9))
5
outputs:
JavaScript
1
2
1
['apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple']
2
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]
JavaScript
1
3
1
mylist = ["apple", "banana", "cherry"]
2
print(random.choices(mylist, cum_weights=[10, 15, 16], k=14))
3
JavaScript
1
2
1
['apple', 'banana', 'cherry', 'banana', 'apple', 'banana', 'apple', 'apple', 'banana', 'banana', 'apple', 'banana', 'banana', 'banana']
2