Build a Probability Calculator Project - Build a Probability Calculator Project

Tell us what’s happening:

Could someone please help me understand what is wrong with this code. It returns a percentage how the test cases want it, yet 2-4 still fail. Someone please help. Thank you.

Your code so far

import copy
import random

class Hat:
    def __init__(self, **kwargs):
        self.colors = dict(kwargs.items())
        self.contents = [ball for ball, count in self.colors.items() for _ in range(count)]
    def draw(self, amount):
        drawn = []
        copied_list = self.contents.copy()
        if amount >= len(copied_list):
            while self.contents:
                ball = random.choice(copied_list)
                copied_list.remove(ball)
                drawn.append(ball)
        else:
            for _ in range(amount):
                ball = random.choice(copied_list)
                copied_list.remove(ball)
                drawn.append(ball)
        # print(f"-->{self.contents}")
        # print(f"^^^{copied_list}")
        return drawn

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    times_found = 0
    for i in range(num_experiments):
        drawn_balls = {}
        balls = [ball for ball in hat.draw(num_balls_drawn)]
        for ball in balls:#Add balls to drawn_balls
            if not ball in drawn_balls:
                drawn_balls[f"{ball}"] = 1#Creates new key in dict if not exists
            else:
                drawn_balls[f"{ball}"] += 1#Increments value if key exists
        found = True
        for key in expected_balls.keys():#loop through expected balls keys
            if key in drawn_balls.keys():#check if expected key is in drawn ball
                    if drawn_balls[key] >= expected_balls[key]:
                        continue
                    else:
                        found = False
        if found:
            times_found += 1

    percentage = times_found / num_experiments
    return f"{percentage:.3f}"




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/134.0.0.0 Safari/537.36 Edg/134.0.0.0

Challenge Information:

Build a Probability Calculator Project - Build a Probability Calculator Project

hat = Hat(black=6, red=4, green=3)
print(len(hat.contents))
hat.draw(3)
print(len(hat.contents))

the hat.contents is the same before and after the draw, you are not removing balls from the hat

Yes, thank you. That managed to fix #2 and #3 but #4 ( The
experiment method should return a different probability. I don’t understand what the errors below are saying. If it is just the TypeError, which things aren’t the correct type?

Error I get.
self.assertAlmostEqual(actual, expected, delta = 0.01, msg = ‘Expected experiment method to return a different probability.’)
batched @ pyodide.asm.js:9
pyodide.asm.js:9 File “/lib/python311.zip/unittest/case.py”, line 904, in assertAlmostEqual
batched @ pyodide.asm.js:9
pyodide.asm.js:9 diff = abs(first - second)
batched @ pyodide.asm.js:9
pyodide.asm.js:9 ^~
batched @ pyodide.asm.js:9
pyodide.asm.js:9 TypeError: unsupported operand type(s) for -: ‘str’ and ‘float’

you have something that is a str type and should not be. I would guess your probability, but I don’t know

what is your code now?

1 Like

Yes you are completely right. It was the probability. I was returning it as an f-string when it should have been a float
I changed f"{float(M) / float(num_experiments):.3f}"
into float(M/num_experiments)
I don’t think the decimal formatting mattered since it just accepted my solution. Thank you so much. It was an obvious error but you helped me see it.
FINALLY DONE with this whole certificate. :slight_smile:

2 Likes