Scientific Computing with Python Projects - Probability Calculator

Tell us what’s happening:
In the last test my probability comes out to 0.259 instead of the expected 0.272, and i dont know why.

Your code so far

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 i in range(value):
                self.contents.append(key)

    def draw(self, num_drawn):
        if num_drawn > len(self.contents):
            return
        self.drawn_balls = []
        for i in range(num_drawn):
            randint = random.randint(0,len(self.contents)-1)
            self.drawn_balls.append(self.contents[randint])
            self.contents.pop(randint)
        return self.drawn_balls
    def return_balls(self):
        for i in self.drawn_balls:
            self.contents.append(i)

def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
    
    m = 0
    
    for i in range(0, num_experiments):
        hat.draw(num_balls_drawn)
        hits = 0
        for color, count in expected_balls.items():
            if hat.drawn_balls.count(color) >= count:
                hits += 1
        if hits == len(expected_balls):
            m += 1
        hat.return_balls()
        
    return m / num_experiments

Your browser information:

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

Challenge: Scientific Computing with Python Projects - Probability Calculator

Link to the challenge:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

Remember that each experiment is supposed to start with the same balls in the hat.

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