杨辉三角
示例:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
题解:我们可以将1提出来,只计算不等于1的值就很好解决了,每一个数都等于上一行的对应下标数加上前一个,如此就有了:
lt = []
num = int(input('请输入层数:'))
for i in range(num):
if i == 0:
ylt = [1]
lt.append(ylt)
elif i == 1:
xlt = [1,1]
lt.append(xlt)
elif i not in (0,1):
xlt = []
for j in range(i+1):
if j == 0:
xlt.append(1)
elif j == i:
xlt.append(1)
elif j not in (0,i):
x = j-1
xi = i - 1
y = lt[xi][x]+lt[xi][j]
xlt.append(y)
lt.append(xlt)
print(lt)


浙公网安备 33010602011771号