在其他功能中调用函数

时间:2013-11-22 03:31:21

标签: python function python-2.7 call

我是函数的新手,我正在试图弄清楚如何从一个函数中获取另一个函数的值。这是布局:我定义了一个函数来提取随机数并将它们放入字典:

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次运行。 问题A:包中的颜色总数正确1次,错误9次(正确率10.0%)

到目前为止一切顺利。现在我想知道它比r多得多少次。我试过模仿第二个函数,但它不识别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?

1 个答案:

答案 0 :(得分:1)

您的第二个函数不需要循环,您可以直接比较字典"r""b"键对应的值:

def evaluateQuestion2(draw):
    return draw["r"] < draw["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