Pascal三角形的Python定制

时间:2017-02-03 20:03:45

标签: python recursion pascals-triangle

我有一个Pascal的三角形(排除前两个元素)和自定义三角形:

 P=[[1, 2, 1],
 [1, 3, 3, 1],
 [1, 4, 6, 4, 1],
 [1, 5, 10, 10, 5, 1],
 [1, 6, 15, 20, 15, 6, 1]]

第二个Pascal是:

 P2=[[2],
 [2, 2],
 [2, 4, 2],
 [2, 6, 6, 2],
 [2, 8, 12, 8, 2],
 [2, 10, 20, 20, 10, 2]]

但我想生成一个新的自定义Pascal三角形,如下式:

-get P[0][1]
-add it to P2[0]
-write again P[0][1] as 4.

-get P[1][1]
-add it to P2[0]
-add it to P[0][0:2]
-write again P[1][1] as 7.

最后一个场景将是递归的。

结果如下:

 newpascal=[[1, 4, 1],
 [1, 7, 7, 1],
 [1, 10, 18, 10, 1],
 [1, 13, 34, 34, 13, 1],
 [1, 16, 55, 80, 55, 16, 1]]

我的代码不起作用:

#Definition of classical Pascal's Triangle   
def pascal1(n):
    if n == 0:
        return [[1]]
    else:
        final_r = pascal1(n - 1)
        last = [0] + final_r[-1] + [0] # note: this does not modify final_r
        new_row = [last[k] + last[k - 1] for k in range(1, len(last))]
        return final_r + [new_row]
p=pascal1(10)

#Definition of Pascal's Triangle (Times2X)
def pascal2(n):
    if n == 0:
        return [[2]]
    else:
        final_r = pascal2(n - 1)
        last = [0] + final_r[-1] + [0] # note: this does not modify final_r
        new_row = [last[k] + last[k - 1] for k in range(1, len(last))]
        return final_r + [new_row]
p2=pascal2(10)


#My Custom Pascal
def newpascal(n):
    final_r = pascal1(n - 1)
    last = [0] + final_r[-1] + [0] # note: this does not modify final_r
    new_row = [last[k] + last[k - 1]+p2[0][0] for k in range(1, len(last))]
    return final_r + [new_row]

1 个答案:

答案 0 :(得分:0)

我完成了几乎难以理解的指示,并提出了以下建议:

def newpascal(n):
    array = pascal1(1)[1]
    p2 = pascal2(n)
    p3 = [list(array)]

    for x, row in enumerate(range(3, n + 2), start=0):

        array.append(1) # both widen the row and initialize last element

        # fill in the row, right to left
        for y, i in enumerate(range(row - 2, 0, -1)):
            # current computed from previous + p2
            array[i] += array[i - 1] + p2[x][y]

        p3.append(list(array))

    return p3

不幸的是,它不是递归的。但它似乎有效:

>>> p3 = newpascal(10)
>>> print(*p3, sep='\n')
[1, 1]
[1, 4, 1]
[1, 7, 7, 1]
[1, 10, 18, 10, 1]
[1, 13, 34, 34, 13, 1]
[1, 16, 55, 80, 55, 16, 1]
[1, 19, 81, 155, 155, 81, 19, 1]
[1, 22, 112, 266, 350, 266, 112, 22, 1]
[1, 25, 148, 420, 686, 686, 420, 148, 25, 1]
[1, 28, 189, 624, 1218, 1512, 1218, 624, 189, 28, 1]
>>> 

在您的解释中,pascal1()是一个红色的鲱鱼,因为它不需要解决这个问题。您只需要从[[1, 1]]开始。那么现在是时候让我们了解你解决的“伟大模式”了!