Daniel Richter
Daniel Richter

Reputation: 353

Choosing items from a list on a percentual basis

I have a list with around 40 strings and want to assign every item a weight / percentage. During runtime I now want a randomizer to pick an item from the list according to its percentage. Meaning that over a large enough sample size the number of times this item gets picked would correspond to the assigned percentage. A problem that I'm facing is that in the future I might want to extend the list and would then have to assign a new percentage to other items. What would be the best way to save this list and assign weights to individual items?

I can think of some ways to implement this but they are all rather quick & dirty so I was hoping somebody has a design pattern in mind. I'm working in Python but since this is conceptual I'm not really fishing for explicit examples.

Thank you so much for your help.

Upvotes: 3

Views: 1893

Answers (2)

dusan
dusan

Reputation: 9273

Check out this page: Weighted random generation in Python

Edit: See this also (on SO): A weighted version of random.choice

Upvotes: 3

nmichaels
nmichaels

Reputation: 50943

One way to do it is to use a range as a dictionary key (perhaps as a 2-tuple) and the string as the value. Then you can use random.randint() to generate an integer in the range described by all the dictionary key values. Adding a new string is easy and its range shoves the others' ranges aside (shrinks their weights). If you don't want that to happen, then you have to re-weight everything anyway.

{
    (0,10): "First string",
    (11,50): "Second string",
    (51,73): "Third string"
}

Upvotes: 1

Related Questions