2013-11-22 153 views
-3

我是新來的函數,我想弄清楚如何從一個函數獲取一個值到另一個函數。這裏的佈局:我定義一個函數來拉隨機數,並把它們放入詞典:在其他函數中調用函數

import random 

def OneSingletDraw(rng): 
    i=0 
    g=0 
    b=0 
    y=0 
    r=0 
    w=0 
    bk=0 

    while i<20: 
     x = rng.randint(1,93) 
     if x<=44: 
      g=g+1 
     elif 44<x<=64: 
      b=b+1 
     elif 64<x<=79: 
      y=y+1 
     elif 79<x<=90: 
      r=r+1 
     elif 90<x<=92: 
      w=w+1 
     else: 
      bk=bk+1 
     i=i+1 
    D = {} 
    D['g'] = g 
    D['b'] = b 
    D['y'] = y 
    D['r'] = r 
    D['w'] = w 
    D['bk'] = bk 

    return D 

現在,我所定義的第二功能給我上面的功能得到了上述變量的6倍。它看起來像:

def evaluateQuestion1(draw): 
    # return True if draw has it right, False otherwise 
    colorcount = 0 
    for color in draw: 
     if draw[color] > 0 : colorcount += 1 
    if colorcount == 6: return True 
    else: return False 

與最後部分是:

if __name__ == "__main__": 
    n = 1000 
    rng = random.Random() 
    Q1Right = 0 
    Q1Wrong = 0 
    for i in xrange(n) : 
     D = OneSingletDraw(rng) 
     if evaluateQuestion1(D) : Q1Right += 1 
     else: Q1Wrong += 1 
    print "Did %d runs"%n 
    print "Got question A: total number of colors in bag right %d times, wrong %d times (%.1f %% right)"%(Q1Right, Q1Wrong, 100.*float(Q1Right)/float(n)) 

它輸出是這樣的:有沒有10次,爲單線策略。 得到的問題答:袋中的顏色總數爲1次,錯誤9次(10.0%右)

到目前爲止好。現在我想知道它有多少次比b多得多。我試圖模仿第二個功能,但它不承認b

def evaluateQuestion2(draw): 
    # return True if draw has it right, False otherwise 
    for r in draw: 
     if draw[r] < b : return True 
    else: return False 

如何讓我的下一個功能從早期識別B'

def evaluateQuestion2(draw): 
    return draw["r"] < draw["b"] 

無關您的問題:

+1

林不知道我認識b兩種。你沒有在你發佈的代碼中的任何地方定義它。但問題幾乎肯定會與範圍有關。你必須在函數外部定義一個變量,以便在函數完成之後保持它。 b如何獲得第一個功能?你是否將它作爲參數傳入? – hammus

回答

1

你不需要在你的第二個功能的循環,你可以對應於你的字典的"r""b"鍵直接比較值,你也許可以簡化您的通過使詞典前面和更新其值,而不是把值最初在獨立的變量,然後構建字典在最後得出代碼:

def OneSingletDraw(rng): 
    D = dict.fromkeys(["g", "b", "y", "r", "w", "bk"], 0) # build the dict with 0 values 

    for _ in range(20): # use a for loop, since we know exactly how many items to draw 
     x = rng.randint(1,93) 
     if x <= 44: 
      D["g"] += 1 # access the value in the dict, using += to avoid repetition 
     elif x <= 64: # no need for a lower bound, smaller values were handled above 
      D["b"] += 1 
     elif x <= 79: 
      D["y"] += 1 
     elif x <= 90: 
      D["r"] += 1 
     elif x <= 92: 
      D["w"] += 1 
     else: 
      D["bk"] += 1 

    return D 
+1

爲此,您需要計算在if __name__ ==「__main __」塊中循環中重複調用「evaluateQuestion2」函數的結果。 – Blckknght

相關問題