Python Forum
random question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: random question (/thread-28516.html)



random question - DPaul - Jul-22-2020

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


RE: random question - buran - Jul-22-2020

Look at https://stackoverflow.com/questions/4265988/generate-random-numbers-with-a-given-numerical-distribution

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


RE: random question - DPaul - Jul-22-2020

(Jul-22-2020, 07:31 AM)buran Wrote: Look at https://stackoverflow.com/questions/4265988/generate-random-numbers-with-a-given-numerical-distribution

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

OK, this answers the question.
Thanks
Paul