0

So if the array I made to simulate picking a coloured ball from a bag looked like this:

A = ["Blue", "Green", "Yellow"]

then I could just use the

random.choice()

function to simulate picking one from the bag. But if I had a different amount of coloured balls in the bag (say 3 green, 5 blue and 10 yellow), how could I make the random choice from the array reflect the different probabilities of picking each colour?

martineau
  • 119,623
  • 25
  • 170
  • 301
Mon
  • 19
  • 4
  • Welcome to Stack Overflow! Please show the code that you have tried and the issues that you have with it. – Mark Skelton Dec 22 '16 at 23:06
  • 5
    This is trivial to research. See e.g. http://stackoverflow.com/q/3679694/3001761 (or just actually put 18 entries in the list...) – jonrsharpe Dec 22 '16 at 23:10
  • "say 3 green, 5 blue and 10 yellow" so `['green']*3 + ['blue']*5 + ['yellow']*10` are all the balls in your bag and then you want to make a choice of those? hmmm... – Tadhg McDonald-Jensen Dec 22 '16 at 23:17
  • @jonrsharpe Thanks for the link. Could you explain how the code works and, if possible, how it can be adapted to other situations? – Mon Dec 22 '16 at 23:45
  • No, that would be too broad for a question, let alone comments! – jonrsharpe Dec 23 '16 at 09:36

1 Answers1

2

Simple, you put the ball in the bag many times

b = "Blue"
g = "Green"
y = "Yellow"
A = []

def append_balls(list, color, quantity):
    for i in range(quantity):
        list.append(color)

append_balls(A, b, 5)
append_balls(A, g, 3)
append_balls(A, y, 10)

print(A)
# A = ['Blue', 'Blue', 'Blue', 'Blue', 'Blue', 'Green', 
#      'Green', 'Green', 'Yellow', 'Yellow', 'Yellow', 'Yellow',
#      'Yellow', 'Yellow', 'Yellow', 'Yellow', 'Yellow', 'Yellow']

Now you can use random.choice(A) to select a random ball from the bag.

Mark Skelton
  • 3,663
  • 4
  • 27
  • 47
Lucas
  • 6,869
  • 5
  • 29
  • 44