I would like to learn how to select weighted items. For example : I want to fetch questions from a pool but if some one can’t give right answer to a question, that causes this question to double its weight and increase the probability of being selected again later on.
Share
Have a class which keeps the item:weight pairs (key=item:value=weight) in a hash table.
The class should also maintain a
total_weightvariable, which is the sum of all the weights in the hash table. The class’ methods toadd_item,remove_item, andupdate_weightfor an item should keep the total_weight updated. This avoids having to recalculate the total for every choice.To choose an item:
Use a random number such that
1<=random_number<=total_weight.Iterate over the item:weight pairs in the hash table, summing the weights until the random number is <= that running sum. When that happens, the key of the pair you’re on is the chosen item.
This is like rolling an imaginary die whose size is the sum of all the weights. For every roll, each item has its own range of numbers on the die, with the size of each range equal to its item’s weight. If the roll result falls within an item’s range, that item is the chosen one.
Editing to add the following sample code after the request in the comment below. Tested this with Python 2.5.2:
And here is the output: