-3

Sorry If there is already a question of this but I didn't find it. So is there function that picks something from a list but with percents like we have a list with a soda, a soup and a water bottle so the program must pick one of these but the chance it would pick the soup is 2% for the soda is 30% and for the water bottle is 68%?

AlphaVxV
  • 15
  • 4

2 Answers2

1

You want to randomly select an element from a list with a specified probability. You can do that using numpy's random.choice function:

options = ['soup', 'soda', 'water']
probs = [0.02, 0.3, 0.68] 
np.random.choice(options, p=probs)

In this example np.random.choice is randomly choosing from a list (options) with some assigned probability (probs). For more info you can see the numpy documentation here: numpy.random.choice.

Cassie
  • 371
  • 3
  • 5
-1

You could use a random number generator to get a random floating number from 0 to 1. If the number is part of 0 to 0.3 you the first item in your list. If the number is part of 0.3 to 0.97 you pick the second item. Otherwise pick the last item.

Yacine Mahdid
  • 723
  • 5
  • 17