2013-11-22 150 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

相关问题