Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to allocate a portion of numbers to an item, using RNG?

So my following code sets the x a random number with the help of the randint from random library, and then i loop while is not a specific number and how many times until it finds it.

from random import *

x = randint(1, 1000)
i = 1
while (x!=1):
   i = i+1
   x = randint(1, 1000)

print(i)

So what i want to do is having a color, lets say red allocated 500 times from 1 to 1000 eg: 1~500 print ("red color") 501~1000 print ("white color")

What approach should i follow?
Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use the random.choices function with the weights argument.

For example:
random.choices(["Red", "White"], weights=[10, 1])

This meaning Red will be more likely than White.

Note that you can choose between the weights argument or the cum_weights argument.

If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using itertools.accumulate()). For example, the relative weights [10, 5, 30, 5] are equivalent to the cumulative weights [10, 15, 45, 50]. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading