Home > Software design >  How to allocate a portion of numbers to an item, using RNG?
How to allocate a portion of numbers to an item, using RNG?

Time:11-06

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!

CodePudding user response:

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.

  • Related