Skip to content
Advertisement

A weighted version of random.choice

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:

JavaScript

This function seems overly complex to me, and ugly. I’m hoping everyone here can offer some suggestions on improving it or alternate ways of doing this. Efficiency isn’t as important to me as code cleanliness and readability.

Advertisement

Answer

Since version 1.7.0, NumPy has a choice function that supports probability distributions.

JavaScript

Note that probability_distribution is a sequence in the same order of list_of_candidates. You can also use the keyword replace=False to change the behavior so that drawn items are not replaced.

Advertisement