Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement biased random function?

Tags:

python

My question is about random.choice function. As we know, when we run random.choice(['apple','banana']), it will return either 'apple' or 'banana' with equal probabilities, what if I want to return biased result, for example, rerurn 'apple' with 0.9 probability and 'banana' with 0.1 probability? How to implement this?

like image 350
peter cai Avatar asked Jun 15 '26 07:06

peter cai


1 Answers

Luckily, in Python 3, you can simply use

import random
random.choices(a, probability)
#random.choices(population, weights=None, *, cum_weights=None, k=1)
like image 72
TracyYXChen Avatar answered Jun 18 '26 01:06

TracyYXChen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!