selection based on percentage weighting

后端 未结 13 2110
忘掉有多难
忘掉有多难 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 14:18

    def weighted_choice(probabilities):
        random_position = random.random() * sum(probabilities)
        current_position = 0.0
        for i, p in enumerate(probabilities):
            current_position += p
            if random_position < current_position:
                return i
        return None
    

    Because random.random will always return < 1.0, the final return should never be reached.

提交回复
热议问题