Mar-19-2019, 11:19 PM
It's a way to do a weighted random selection. You have a dictionary of words and their weight (the value). You make a random number from 1 to the total of the weights (that's what is in randIndex). Then you go through the words and subtract each word's value from randIndex (
In 3.6+, the random module has choices, which can handle this for you more efficiently. However, prior to that you have to use code like the above.
randIncex -= value
is equivalent to randIndex = randIndex - value
). When randIndex gets to zero or less, that is your weighted random choice. It makes it so that a word with value v is selected with a probability v / t, where t is the sum of all the values.In 3.6+, the random module has choices, which can handle this for you more efficiently. However, prior to that you have to use code like the above.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures