我用Python创建了一个Monty Hall程序(证明了2/3到1/3的几率),但当我尽可能少地创建它时(我的个人兴趣)我得到了这些神秘的错误!这是代码:
from random import *
i,a,abc,t,m=choice(['A','B','C']),raw_input('Switch? (y/n): ').upper(),['A','B','C'],0,0
for j in range(100):
p = choice(abc)
if ([y for y in abc if y not in [i,(choice([x for x in abc if x not in [i,p]]))]][0] if a == 'Y' else i) == p : t += 1
print 'WP: %i\nErrors: %i' %(t,m)
我收到了这个错误:
Traceback (most recent call last):
File "fewlinesMonty.py", line 5, in <module>
if ([y for y in abc if y not in [i,(choice([x for x in abc if x not in [i,p]]))]][0] if a == 'Y' else i) == p : t += 1
IndexError: list index out of range
所以,我使用try / except来计算使用此代码的错误:
from random import *
i,a,abc,t,m=choice(['A','B','C']),raw_input('Switch? (y/n): ').upper(),['A','B','C'],0,0
for j in range(100):
p = choice(abc)
try:
if ([y for y in abc if y not in [i,(choice([x for x in abc if x not in [i,p]]))]][0] if a == 'Y' else i) == p : t += 1
except: m += 1
print 'WP: %i\nErrors: %i' %(t,m)
错误从不超过10%,但这对我没有意义!
要修复错误,所有必要的是定义
o = choice([x for x in abc if x not in [i,p]])
然后用o。
替换相应的代码我知道代码很难(有点不可能)阅读,但我感谢任何帮助/建议。
编辑: 以下是变量的含义: i =初始门选择(随机)x =要打开的门(不是奖品,不是初始)y =要切换到的门(不是x,不是初始)abc =列表中的AB和C t =总赢得m =神秘的错误p =奖品(或&#39; car&#39;)的门是
答案 0 :(得分:0)
更直接一点有什么不妥?
from random import choice
initial_guess, flip, wins=choice('ABC'),input('Switch? (y/n): ').upper()=="Y",0
for _ in range(100):
actual_winner = choice('ABC')
wins += 1 if (initial_guess == actual_winner and not flip) or (flip and initial_guess != actual_winner) else 0
print("WP: ", wins)
运行1
Switch? (y/n): y
WP: 62
运行2
Switch? (y/n): n
WP: 31
如果你真的想要最少的线:
from random import choice
initial_guess, flip = choice('ABC'), input('Switch? (y/n): ') in ['y','Y']
print("WP: ", sum([[0,1],[1,0]][flip][initial_guess==choice('ABC')] for _ in range(100)))
答案 1 :(得分:0)
感谢RobertB解决这个问题,这里是:(我确实做了一些次编辑)
from random import choice
initial_guess, flip = choice('ABC'), raw_input('Switch? (y/n): ') in ['y','Y']
print "WP: " , sum([[0,1],[1,0]][flip][initial_guess==choice('ABC')] for i in range(100))