我怎样才能提高这个monty hall程序的速度,有趣的是,使用BBC BASIC for Windows编写的相同代码在Python代码的一半时间内完成了任务。
Python代码:
import random
t = 10000001
j = 0
k = 0
for a in range(1, t):
p = int(random.random() * 3) + 1
g = int(random.random() * 3) + 1
if p == g:
r = int(random.random() * 2) + 1
if p == 1:
r += 1
if p == 2 and r == 2:
r = 3
else:
r = p ^ g
s = g
f = g ^ r
if s == p:
j = j + 1
if f == p:
k = k + 1
print(f"After a total of {t - 1} trials,")
print(f"The 'sticker' won {j} times ({int(j/t*100)}%)")
print(f"The 'swapper' won {k} times ({int(k/t*100)}%)")
BBC BASIC for Windows code
T% = 10000000
for A% = 1 to T%
P% = rnd(3)
G% = rnd(3)
if P% = G% then
R% = rnd(2)
if P% = 1 then R% += 1
if P% = 2 and R% = 2 then R% = 3
else
R% = P% eor G%
endif
S% = G%
F% = G% eor R%
if S% = P% then J% = J% + 1
if F% = P% then K% = K% + 1
next
print "After a total of ";T%;" trials,"
print "The 'sticker' won ";J%;" times (";int(J%/T%*100);"%)"
print "The 'swapper' won ";K%;" times (";int(K%/T%*100);"%)"
答案 0 :(得分:1)
第一件事是更改您的导入来源:
let options = {
caption: (trigger) => trigger.querySelector('img').getAttribute('data-caption');
}
到
import random
然后使用:
from random import random
您可以做的第二件事是更改您的
p = int(random() * 3) + 1
g = int(random() * 3) + 1
进入:
if s == p:
j = j + 1
if f == p:
k = k + 1