更好的计算概率的方法?
Better way of computing probabilities?
好的。我正在处理的任务是通过改变赢得游戏的支出来使游戏公平。
为了验证游戏现在是否更公平,我在同一个程序中有多个相同代码的实例。这是因为代码使用了 random 模块,并且通过打印这些段中的每一个,我会得到不同的输出,即使它是相同的代码。
唯一的区别是函数的名称。
现在,我想知道:有没有更好的方法来做到这一点?一遍又一遍地重复相同的功能是非常丑陋的,并且它使代码由许多行组成。
我对此很陌生,非常感谢您提供帮助,使我的代码更高效、更短。
除了 balance_sumdiceX(N, r)
函数和重复的 print
语句之外,您可以看到我代码的各个方面。
我在这里提供了代码图片:
First section of code
Second section of code, mainly print statements
函数的全部意义在于允许代码重用。为什么不将所有这些函数调用放在一个循环中。
for trial in xrange(num_trials): # replace with the number of trials you want
print 'After playing the game %d times, your balance will be %d' % (N, balance_sumdice(N, r))
你不需要定义做同样事情的不同方法,只用一个
from random import randint
import sys
def balance_sumdice(N, r):
w = 100
for reps in xrange(N):
s = 0
for dice in xrange(4):
outcome = randint(1,6)
s += outcome
if s < 9:
w += r-1
else:
w -= 1
return w
def prob_sumdice(N):
M = 0
for reps in xrange(N):
s = 0
for dice in xrange(4):
outcome = randint(1,6)
s += outcome
if s < 9:
M += 1
return float(M)/N
N = int(sys.argv[1])
r = float(sys.argv[2])
PW = 100*prob_sumdice(N)
PL = 100 - PW
print 'Your chance of winning is %.1f, aka the chance of losing is %.1f' % (PW,PL)
for x in range(1,10):
print 'After playing the game %d times, your balance will be %d' % (N, balance_sumdice(N,r))
好的。我正在处理的任务是通过改变赢得游戏的支出来使游戏公平。 为了验证游戏现在是否更公平,我在同一个程序中有多个相同代码的实例。这是因为代码使用了 random 模块,并且通过打印这些段中的每一个,我会得到不同的输出,即使它是相同的代码。 唯一的区别是函数的名称。
现在,我想知道:有没有更好的方法来做到这一点?一遍又一遍地重复相同的功能是非常丑陋的,并且它使代码由许多行组成。
我对此很陌生,非常感谢您提供帮助,使我的代码更高效、更短。
除了 balance_sumdiceX(N, r)
函数和重复的 print
语句之外,您可以看到我代码的各个方面。
我在这里提供了代码图片:
First section of code
Second section of code, mainly print statements
函数的全部意义在于允许代码重用。为什么不将所有这些函数调用放在一个循环中。
for trial in xrange(num_trials): # replace with the number of trials you want
print 'After playing the game %d times, your balance will be %d' % (N, balance_sumdice(N, r))
你不需要定义做同样事情的不同方法,只用一个
from random import randint
import sys
def balance_sumdice(N, r):
w = 100
for reps in xrange(N):
s = 0
for dice in xrange(4):
outcome = randint(1,6)
s += outcome
if s < 9:
w += r-1
else:
w -= 1
return w
def prob_sumdice(N):
M = 0
for reps in xrange(N):
s = 0
for dice in xrange(4):
outcome = randint(1,6)
s += outcome
if s < 9:
M += 1
return float(M)/N
N = int(sys.argv[1])
r = float(sys.argv[2])
PW = 100*prob_sumdice(N)
PL = 100 - PW
print 'Your chance of winning is %.1f, aka the chance of losing is %.1f' % (PW,PL)
for x in range(1,10):
print 'After playing the game %d times, your balance will be %d' % (N, balance_sumdice(N,r))