2016-11-18 127 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