Tell us what’s happening:
My code fail on the third test, please help to review it… I have put the logic in the comment for each line. Thanks in advance guys…
Your code so far
import copy
import random
from collections import Counter
class Hat:
def __init__(self,**balls):
self.contents = []
for k,v in balls.items():
for _ in range(v):
self.contents.append(k)
# self.drawballs = []
def draw(self,numofballs):
# set an empty list for result
drawballs = []
# get number of balls
maxindex = len(self.contents)
# if numofballs > len of content then return all the ball
if numofballs >= len(self.contents) : drawballs = self.contents
else:
# looping numofballs times
for _ in range(numofballs):
# pop the balls with random index numbofballs times
self.drawballs.append(self.contents.pop(random.randint(0,maxindex-1)))
maxindex -= 1
return drawballs
def experiment(hat, expected_balls, num_balls_drawn, num_experiments):
prob = 0.0
good = 0
# looping num_experiments times
for _ in range(num_experiments):
hat_copy = copy.deepcopy(hat)
# since expected_balls is dictionary, convert drawn to dict
drawn = dict(Counter(hat_copy.draw(num_balls_drawn)))
counter_color = 0
counter_value = 0
for color in expected_balls:
# check if color in expected is exist
if color in drawn:
# if exist then add counter for color
counter_color += 1
# check if all colors in expected are exist in drawn
if counter_color == len(expected_balls):
for color in expected_balls:
# check if each value in expected
# is less/equal value in drawn
if expected_balls[color] <= drawn[color]:
# if each color fulfill the requirement then
# add counter of value
counter_value +=1
# check if number of value also
# the same as number of item in expected
if counter_value == len(expected_balls):
good +=1
prob = good/num_experiments
return prob
Your browser information:
User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36
Challenge Information:
Scientific Computing with Python Projects - Probability Calculator