Probability Calculator Problem

I’m having some trouble getting the last test to pass. I keep gettin a result near to 0.193, but can’t see an error in my logic. I’ve tried using different methods for random selection (random.choice(), randint(), sample(), random()), and have tried different approaches to copying to reset the contents.

import copy
import random
# Consider using the modules imported above.

class Hat:
  def __init__(self, **kwargs):
    self.contents = [] 
    for key, value in kwargs.items():
      for n in range(value):
        self.contents.append(key)
  

  def draw(self, num):
    # if num too big, return all
    if num >= len(self.contents):
      return self.contents

    # random selection
    selection = []
    for n in range(num):
      choice = random.choice(self.contents)
      selection.append(choice)
      self.contents.remove(choice)

    return selection

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
  contents = copy.deepcopy(hat.contents)
  
  # collect the experiment results
  count_matches = 0

  for exp in range(num_experiments):
    hat.contents = copy.deepcopy(contents)
    result = hat.draw(num_balls_drawn)
    result = {ball:result.count(ball) for ball in result}
    print(result)

  # compare results to expectation
    is_match = True
    for ball, count in result.items():
      if ball not in expected_balls:
        is_match = False
      elif count < expected_balls.get(ball):
        is_match = False

    if is_match:
      count_matches += 1
  
  return count_matches/num_experiments

Since your probability is low, the first thing to check is if you are disallowing positive results unintentionally. If you change the test at the end like this:

    if is_match:
      count_matches += 1
    else:
      print(f"result:  {result}")
      print(f"expected:  {expected_balls}")

You can check for cases like this:

result:  {'blue': 2, 'red': 1, 'green': 1}
expected:  {'blue': 2, 'red': 1}

which should pass but don’t because this test

      if ball not in expected_balls:
        is_match = False
      elif count < expected_balls.get(ball):
        is_match = False

fails at the green ball because it’s not in the expected set but the expectation is actually met since there are sufficient blue and red balls. Fixing the test that checks the draw does pass all the tests (verified with my test and your code).

Thank you so much for your help, I was beating my head against this for a couple days and couldn’t figure it out. I’ve got it fixed now.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.