问题描述
这是我为挑战而写的代码
挑战链接:
import random
def list_to_dict(input_list):
dictionary = {}
for element in input_list:
if element in dictionary:
dictionary[element] += 1
else:
dictionary[element] = 1
return dictionary
class Hat():
def __init__(self,**kwargs):
if len(kwargs) >= 1:
self.__dict__.update(kwargs)
contents = []
for key,value in self.__dict__.items():
for i in range(int(value)):
contents.append(key)
self.contents = contents
def print_contents(self):
print(self.__dict__)
def draw(self,number_of_balls):
if number_of_balls >= len(self.contents):
return self.contents
else:
return_balls = []
for i in range(number_of_balls):
x = len(self.contents) - 1
index = random.randint(0,x)
return_balls.append(self.contents[index])
self.contents.pop(index)
return return_balls
def experiment(hat,expected_balls,num_balls_drawn,num_experiments):
N = num_experiments
M = 0
for i in range(N):
res = hat.draw(num_balls_drawn)
res_dict = list_to_dict(res)
count = 0
for k,v in expected_balls.items():
if res_dict.get(k) == None or res_dict.get(k) < v:
count += 1
if count == 0:
M += 1
return M / N
它可以作为示例运行
hat = Hat(blue=3,red=2,green=6)
print(experiment(hat=hat,expected_balls={"blue":2,"green":1},num_balls_drawn=4,num_experiments=1000))
在我上面给出的例子中,experiment
函数的返回值应该在 0.272
左右,但它几乎总是返回 0.0
。谁能帮我解释一下为什么会这样?谢谢
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)