递归循环的输出不一致,递归循环将中间结果存储在字典中

时间:2019-07-12 11:11:07

标签: python recursion

我有一个问题,根据我用默认值调用函数的方式,使用相同参数运行定义的函数会得到不同的结果。

我有一个函数theEnd(n,C),该函数计算某些递归定义的函数testFunc的总和。 testFunc会在计算出的字典中跟踪先前完成的计算。

testFunc定义为:

def testFunc(var, loopVar, param, computed = {(0,0) : 1, (0,1) : 1}):
    """ Does some recursive calculation for loopVar 
        testFunc(loopVar, var, ...) = sum over var: var * testFunc(loopVar - 1, var, ...)
        sum goes from 0 <= var < param
        tracks all previously done calculations in computed
    """
    # basecase f(0,0) = 1 and f(0,x) = 1
    if var == 0 and loopVar > 0:
        computed[(var, loopVar)] = 1
    # if not in computed do the recursive implementation and save to computed
    if (var, loopVar) not in computed.keys():
        total = 0
        for i in range(param):
            total += i * testFunc(var-1, i, param, computed)
        computed[(var, loopVar)] = total
    return computed[(var, loopVar)]  

取决于我如何定义theEnd函数的问题,我将获得不一致的结果。我确定这与不调用计算字典的默认值有关,但是为什么我的theEnd要求调用testFunc重新定义默认计算字典?

选项1定义了它对testFunc(n,i,C)求和,而无需调用计算= {((0,0):1,(0,1):1}。

选项2定义了它对testFunc(n,i,C,计算= {{(0,0):1,((0,1):1}))求和

对于n = 3,C = 3和n = 4以及C = 4的选项1输出

(n, C) = (3, 3) : 81
(n, C) = (4, 4) : 1620

选项2输出相同的值

(n, C) = (3, 3) : 81
(n, C) = (4, 4) : 5184

两个不同选项的代码:

选项1

def theEnd(n, C):
    """ computes final results by calculating
        thing = sum over i: testFunc(n, i, C)
        with 0 <= i < C
    """
    thing = 0
    for i in range(C):
        thing += testFunc(n, i, C)
    return thing             

    print("(n, C) =", (3,3), ":", theEnd(3,3))            
    print("(n, C) =", (4,4), ":", theEnd(4,4))

选项2

def theEnd(n, C):
    """ computes final results by calculating
        thing = sum over i: testFunc(n, i, C)     with 0 <= i < C
    """
    thing = 0
    for i in range(C):
        thing += testFunc(n, i, C, computed = {(0,0) : 1, (0,1) : 1})
    return thing             

    print("(n, C) =", (3,3), ":", theEnd(3,3))            
    print("(n, C) =", (4,4), ":", theEnd(4,4))

0 个答案:

没有答案