递归Pascal三角函数的优化

时间:2015-08-24 20:16:57

标签: python

今天我挑战自己尝试实现一个递归函数,它可以产生最多n级的Pascal三角形。我设法提出了一个解决方案,然而,它并不像我想的那样高效或优雅。在下面的代码中,每次我在pascal()中调用pascal_row()时,它都会遍历传递给pascal_row()的任意数量的级别;反对让它通过并在n级建立三角形。我不知道这是否有意义,但这里是代码......无论如何都要对此进行优化吗?

#builds the pascal row for the specified level
#ex. pascal_row(3) --> [1,3,3,1]
def pascal_row(levels):
    if levels == 0:
        return [1]
    elif levels == 1:
        return [1,2,1]
    else:
        row = []
        row.append(1)
        prev = pascal_row(levels-1)
        for i in range(len(prev)):
            try:
                row.append(prev[i] + prev[i+1])
            except:
                pass
        row.append(1)
        return row

#prints out pascal triangle up to specified level
def pascal(levels):
    for lvl in range(levels):
        print(pascal_row(lvl))

if __name__ == "__main__":
    pascal(10)  #outputs correctly

2 个答案:

答案 0 :(得分:1)

我要做的第一件事是缓存中间计算(a.k.a动态编程)。

定义全局变量

pascal_cache={0:[1],1:[1,2,1]}

然后修改pascal_row

def pascal_row(levels):
    if levels in pascal_cache.keys():
        return pascal_cache[levels]
    else:
        row = []
        row.append(1)
        prev = pascal_row(levels-1)
        for i in range(len(prev)):
            try:
                row.append(prev[i] + prev[i+1])
            except:
                pass
        row.append(1)
        pascal_cache[levels]=row
        return row

它应该大大降低代码的复杂性

答案 1 :(得分:-1)

更好:

pascal_reeks={0:[1],1:[1,2,1]}

if n in pascal_reeks:
    return pascal_reeks[n]
else:
    row = []
    row.append(1)
    prev = pascalTriangle(n-1)
    for i in range(len(prev) - 1):
        row.append(prev[i] + prev[i+1])

    row.append(1)
    pascal_reeks[n]=row
    return row