2016-11-18 79 views
-2

好的。我正在从事的任务是通过改变赢得比赛的奖金来使比赛更加公平。 为了验证游戏现在更公平,我在同一个程序中有几个相同代码的实例。这是因为代码使用随机模块,并通过打印每个段,我会得到不同的输出,即使它的代码相同。 唯一的区别是功能的名称。更好的计算概率的方法?

现在,我想知道:有没有更好的方法来做到这一点?这个功能非常难看,重复了相同的功能,并且它使得代码由许多行组成。

我对此很新,并且非常感谢让我的代码更高效和更短的一些帮助。

除了balance_sumdiceX(N, r)函数和重复的print语句外,您可以查看我的代码的每个方面。 我这里提供的代码的图片:

First section of code

Second section of code, mainly print statements

+2

后用正确的格式设置的代码在你的问题不是一个图片 – MooingRawr

+1

可能在http更好属于: //codereview.stackexchange.com/如果你只是想让它更高效 – depperm

+1

如果错误纠正我,是不是所有的方法都是同一个东西?什么阻止你每次只使用一种方法? – nims

回答

0

的功能整点是允许代码重用。为什么不把所有这些函数调用放在一个循环中。

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)) 
+0

非常感谢!这正是我正在寻找的。 –

0

你并不需要定义做同样的事情不同的方法,只需要用一个

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)) 
+0

我想要做几个输出,以表明这次游戏确实更公平。我知道我可以多次运行该程序并记录输出,但我想知道是否有办法做我做的事,没有太多的代码。 –

+0

@JonasNorill你不必多次运行该程序,只需使用循环。 – Mark