我是python的新手。我有这四个相关的功能但最后没有响应。
import ui as numpy
def simulate_prizedoor(nsim):
sim=ui.random.choice(3,nsim)
return sims
def simulate_guess(nsim):
guesses=ui.random.choice(3,nsim)
return guesses
def goat_door(prizedoors, guesses):
result = ui.random.randint(0, 3, prizedoors.size)
while True:
bad = (result == prizedoors) | (result == guesses)
if not bad.any():
return result
result[bad] = ui.random.randint(0, 3, bad.sum())
def switch_guesses(guesses, goatdoors):
result = ui.random.randint(0, 3, guesses.size)
while True:
bad = (result == guesses) | (result == goatdoors)
if not bad.any():
return result
result[bad] = ui.random.randint(0, 3, bad.sum())
如您所见,第三个和四个函数具有相同的代码。
我运行第一个和第二个功能:
a=simulate_prizedoor(4)
b=simulate_guess(4)
print(a)
[2 2 0 2]
print (b)
[2 0 0 2]
然后,我运行第三个函数,其值为a和b
c=goat_door(a,b)
print(c)
[1 1 2 1]
最后,我运行了最后一个函数,但python没有响应,看来这是一个无限的过程来给出答案。
switch_guess(b,c)
编辑:
这是图像:
答案 0 :(得分:1)
您发布的代码存在阻止其运行的错误。请在提问时发布原始未修改的代码 - 您将更有可能获得建设性的反馈和良好的答案。
以下是我发布的代码中发现的错误:
Traceback (most recent call last):
File "montyhall.py", line 1, in <module>
import ui as numpy
ImportError: No module named ui
我猜对了正确的行:import numpy as ui
Traceback (most recent call last):
File "montyhall.py", line 27, in <module>
a=simulate_prizedoor(4)
File "montyhall.py", line 5, in simulate_prizedoor
return sims
NameError: global name 'sims' is not defined
我对正确功能的猜测:
def simulate_prizedoor(nsim):
sim=ui.random.choice(3,nsim)
return sim
你的缩进也有点奇怪。
我运行的更正代码包含在下面。当我运行它时,没有错误,simulate_prizedoor
函数不会卡在循环中。也许您运行的代码存在导致问题的差异?
import numpy as ui
def simulate_prizedoor(nsim):
sim=ui.random.choice(3,nsim)
return sim
def simulate_guess(nsim):
guesses=ui.random.choice(3,nsim)
return guesses
def goat_door(prizedoors, guesses):
result = ui.random.randint(0, 3, prizedoors.size)
while True:
bad = (result == prizedoors) | (result == guesses)
if not bad.any():
return result
result[bad] = ui.random.randint(0, 3, bad.sum())
def switch_guesses(guesses, goatdoors):
result = ui.random.randint(0, 3, guesses.size)
while True:
bad = (result == guesses) | (result == goatdoors)
if not bad.any():
return result
result[bad] = ui.random.randint(0, 3, bad.sum())
a=simulate_prizedoor(4)
b=simulate_guess(4)
print(a)
print (b)
c=goat_door(a,b)
print(c)
d=switch_guesses(b,c)
print(d)