如何生成以下金字塔(预先在第一和第二行中施加了金字塔)?
1
1 4 1
1 5 6 5 1
1 6 12 16 12 6 1
这是我到目前为止尝试过的方法,但是没有用:
def main():
first_row = [1] # given in the question
second_row = [1, 4, 1] # given in the question
sum = 0
n = int(input("Enter number of rows: "))
list_of_rows = list()
list_of_rows.append(first_row)
list_of_rows.append(second_row)
for i in range(2, n):
list_of_rows.append([])
for j in range(0, 2*i+1): # each row is 2 digits bigger than the previous
list_of_rows[i].append(sum)
print(list_of_rows)
答案 0 :(得分:2)
这似乎是斐波那契金字塔的一种变体,其中第二行应改为[1,1]
。
将行添加到序列中的一种简洁明了的方法是将前一行与[1,1,1]
卷积。您可以为此使用np.convolve
:
n = 4
l = [[None]]* n
l[0] = [1]
l[1] = [1,4,1]
for i in range(2,n):
l[i] = list(np.convolve(l[i-1], [1,1,1]))
print(l)
[[1], [1, 4, 1], [1, 5, 6, 5, 1], [1, 6, 12, 16, 12, 6, 1]]
对于标准的斐波那契金字塔,解决方案是:
n = 10
l = [[None]]* n
l[0] = [1]
l[1] = [1,1]
for i in range(2,n):
l[i] = list(np.convolve(l[i-1], [1,1]))
print(l)
[[1], [1, 1], [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], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]