Build a Probability Calculator Project - Build a Probability Calculator Project

Tell us what’s happening:

‘The experiment method should return a different probability.’

I have done the experiement example and i get a value around the expected 0.356 with a 1sigma aprox 0.015 every time i calculate the probability.

i am not sure what i am doing wrong

Your code so far

import random

class Hat:
  def __init__(self,**kwarg):
    a=[]
    for key, value in kwarg.items():
      for i in range(value):
        (a).append(str(key))
    self.contents=a
    self.original=a
  def draw(self,N):
    if N >= len(self.contents):
      drawn=self.contents
      self.contents=[]
    else:
      drawn = random.sample(self.contents, k=N)
      for ball in drawn:
        self.contents.remove(ball)           
    return drawn

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
  N=0
  for i in range(num_experiments):
    drawn=hat.draw(num_balls_drawn)
    if all(drawn.count(f'{key}')>=value for key,value in expected_balls.items()):
      N+=1
    hat.contents.extend(drawn)
  return N/num_experiments



  
hat = Hat(black=6, red=4, green=3)
probability = experiment(hat=hat,
                  expected_balls={'red':2,'green':1},
                  num_balls_drawn=5,
                  num_experiments=2000)

print(probability)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36

Challenge Information:

Build a Probability Calculator Project - Build a Probability Calculator Project

I think the issue is with the way experiment handles keeping the number of balls the same after single experiment. Tests are leveraging fact that random module is not really random, but pseudo-random, it can be seeded with specific number to reproduce results expected by tests. However result of the draw is not only affected by the number of balls in hat, but also the order they are in it. This means adding the drawn balls at the end of hat will give different results in further draws, than when hat would have them in their original order.

1 Like

I got it thanks for the help, only if it were more perfectly random :adhesive_bandage: