A weighted version of random.choice

后端 未结 25 1872
闹比i
闹比i 2020-11-21 06:29

I needed to write a weighted version of random.choice (each element in the list has a different probability for being selected). This is what I came up with:



        
25条回答
  •  渐次进展
    2020-11-21 06:41

    If your list of weighted choices is relatively static, and you want frequent sampling, you can do one O(N) preprocessing step, and then do the selection in O(1), using the functions in this related answer.

    # run only when `choices` changes.
    preprocessed_data = prep(weight for _,weight in choices)
    
    # O(1) selection
    value = choices[sample(preprocessed_data)][0]
    

提交回复
热议问题