Build a Probability Calculator Project - Build a Probability Calculator Project

I am unable to pass the third test case for the probability calculator project. I am pretty sure that I have done it right and have spent a lot of time figuring out the mistake. The rest of the code works properly. Please let me know what am I missing out as this is the last project that needs to be completed for the certification.
~Thanks :slight_smile:

Your code so far

import copy
import random

class Hat:
    def __init__(self, **balls):
        self.contents = []
        for x, y in balls.items():
            while y > 0:
                self.contents.append(x)
                y -= 1
    def draw(self, num):
        removed = []
        if num > len(self.contents):
            return self.contents
        for _ in range(num):
            temp = self.contents.pop(random.randrange(len(self.contents)))
            removed.append(temp)
        return removed

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    final=0
    for _ in range(num_experiments):
      copyhat = copy.deepcopy(hat)
      temp_list = copyhat.draw(num_balls_drawn)
      success=True
      for key,value in expected_balls.items():
        if temp_list.count(key) < value:
          success=False
          break
      if success:
        final+=1
    return final/num_experiments

Your browser information:

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

Challenge Information:

Build a Probability Calculator Project - Build a Probability Calculator Project

2 Likes

can you tell me about what debugging you have done here?

1 Like

Hi! After going through your code, here are a few suggestions:

  1. Modify the draw Method: When the number of balls to draw exceeds or matches the total available, empty the contents array before returning all the balls.
  2. Use random.sample: Replace the current random selection logic with random.sample to select balls without replacement. This makes the code cleaner and avoids direct indexing.
  3. add a Print Statement for Probability: Ensure the result of the experiment function is displayed by adding print(probability) at the end of the example usage.

Let us know if this works.

1 Like

Case Number 3 requests the draw method to โ€œbehave correctly when the number of balls to extract is bigger than the number of balls in the hat.โ€

For that to occur, self.contents list must already be fully empty and have all its items transferred to the removed list in order for you to return all the balls in your removed list.

        if num > len(self.contents):
            return self.contents

The draw method should return removed, as its intent is to โ€œremove balls at random from contents and return those balls as a list of strings.โ€ Should num > len(self.contents), the method would expect you to return an empty list.