Python Forum

Full Version: random question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

Suppose a function that runs over and over again.
At a certain point it calls another function with an argument 'A' or '.B'
Randomly 70% of the time with 'A', 30 % of the time with 'B'. (or any other combination)
The way i implemented this is to make a tuple with the distribution and do a random.choice().
A70pct = ('A','A','A','A','A','A','A','B';'B','B')
c = random.choice(A70pct)
The upside : it is very simple and effective. This will also allow for a third argument 'C', with e.g. a 50-30-20 distribution.etc.
The downside: if i need more than one distribution, like 60-40 or... i need to hard code these tuples.
I could write a function, that creates a tuple on the fly, does the .choice() and returns the result.
But that code then needs to run over and over again, the hard coding beingmore efficient, if there are only a few distributions.

Question: there may be a better way of doing this, an exotic function i never heard of ?

Paul
Look at https://stackoverflow.com/questions/4265...stribution

In your case I think using random.choices is the optimal solution
(Jul-22-2020, 07:31 AM)buran Wrote: [ -> ]Look at https://stackoverflow.com/questions/4265...stribution

In your case I think using random.choices is the optimal solution

OK, this answers the question.
Thanks
Paul