新手求教:请问怎样用python 显示杨辉三角,任意输入一个数N,输出一个N+1层的杨辉三角。
发布网友
发布时间:2022-10-16 08:09
我来回答
共1个回答
热心网友
时间:2023-10-17 10:00
我来试一下:
#!/usr/bin/python
# coding:utf-8
n = -1
while n < 0:
n = raw_input("Enter a nonnegative integer >= 0:")
try:
n = int(n)
except:
print "please enter integer!"
n = -1
tmppascal = [0,]* (2 * n + 3)
pascal = []
for i in range(n + 2):
pascal += [tmppascal[:],]
center = n + 1
pascal[1][center] = 1
x = y = 0
for i in range(2, n + 2):
if n % 2 == 1:
if i % 2 == 0:
x = 1
y = 2 * n + 2
else:
x = 2
y = 2 * n + 1
else:
if i % 2 == 1:
x = 1
y = 2 * n + 2
else:
x = 2
y = 2 * n + 1
for j in range(x, y, 2):
pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j + 1]
if n % 2 == 0:
max = pascal[n + 1][center]
else:
max = pascal[n + 1][center - 1]
maxlen = len(str(max))
for row in pascal[1:]:
for col in row[1:-1]:
if col == 0:
col = ""
fm = '{0: ^' + str(maxlen) + '}'
print fm.format(col),
print