开发者

Randomly selecting an object with a weighted probability in Python [duplicate]

开发者 https://www.devze.com 2023-03-14 17:02 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicates: Random weighted choice
This question already has answers here: Closed 11 years ago.

Possible Duplicates:

Random weighted choice

Select random k elements from a list whose elements have weights

Let's say I have a set of开发者_JAVA百科 N objects,

set = range(a,b) = [a,a+1,...b-2, b-1]

To select M number of objects with probability 1/len(N), I can do:

random.sample(set, M).

I want to able to select objects at random with a weighted probability. For example, if not a multiple of 3 or 5, weighted probability will be 1. If a multiples of 3, weighted probability will be 3, if a multiple of 5, weighted probability will be 5, if a multiple of 15, weighted probability will be 15.

To illustrate:

set = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
weighted_set=[(1, weight=1), (2, weight=1), (3, weight=3),(4, weight=1), (5, weight=5),...(15, weight=15)]
random.sample(weighted_set, N)

How would I do something like this? Thank you.


You can use code like this to weigh items, by just adding them multiple times to a different set.

set = [1,2,3,4,5,6,7,8,9,10]
weight = 5
weighted_set = []
for i in set:  
    if i % 5 == 0:
        weighted_set += weight*[i]
    else:
        weighted_set += [i]
0

精彩评论

暂无评论...
验证码 换一张
取 消