selection based on percentage weighting

后端 未结 13 2097
忘掉有多难
忘掉有多难 2020-12-04 13:40

I have a set of values, and an associated percentage for each:

a: 70% chance
b: 20% chance
c: 10% chance

I want to select a value (a, b, c) based

13条回答
  •  情深已故
    2020-12-04 13:59

    Take the list of and find the cumulative total of the weights: 70, 70+20, 70+20+10. Pick a random number greater than or equal to zero and less than the total. Iterate over the items and return the first value for which the cumulative sum of the weights is greater than this random number:

    def select( values ):
        variate = random.random() * sum( values.values() )
        cumulative = 0.0
        for item, weight in values.items():
            cumulative += weight
            if variate < cumulative:
                return item
        return item # Shouldn't get here, but just in case of rounding...
    
    print select( { "a": 70, "b": 20, "c": 10 } )
    

    This solution, as implemented, should also be able to handle fractional weights and weights that add up to any number so long as they're all non-negative.

提交回复
热议问题