0

Let's say I have a list [0.25,0.25,0.25,0.25]. I want to input this to a function which yields a random number between 0 and 3 with 25 percent of each number.

Something that yields the same as this but takes the form random([0.25,0.25,0.25,0.25])

import random
my_list = ['0'] * 0.25 + ['1'] * 0.25 + ['2'] * 0.25 + ['3'] * 0.25
random.choice(my_list)

Another example is random([0.1, 0.9])

which yields a 10 percent chance of printing '0' and a 90 percent chance of printing '1'

So essentially a general function random(list), which selects a random number between 0 and len(list) - 1 with probability weights being the objects in list

A. Fattal
  • 77
  • 3
  • `random.choices('0123', [25, 25, 25, 25])` – Olvin Roght Feb 20 '21 at 19:52
  • Yeah I know but I need this to be a general function where users input any list – A. Fattal Feb 20 '21 at 19:58
  • To get 20 samples: `random.choices(['first', 'second', 'third', 'fourth'], [25, 25, 25, 25], k=20)`. Or `np.random.choice(['first', 'second', 'third', 'fourth'], size=20, p=[.25, .25, .25, .25])`. – JohanC Feb 21 '21 at 02:10

0 Answers0