我想编写一个Python程序,以打印出输入行数的Pascal Triangle。 我的代码如下:
inc = int(input('Input number of rows: '))
n = 0
row = []
while n <= inc:
m = 11 ** n
row.append(m)
n += 1
for i in range(0, len(row)):
row[i] = str(row[i])
result = '\n'.join(row)
print(result)
我的输出是:
1
11
121
我想将每一行中的每个符号分开,以使其看起来像帕斯卡的三角形。我该如何实现?
答案 0 :(得分:2)
您非常接近,每行只需str.center
:
inc = int(input('Input number of rows: '))
n = 0
row = []
while n < inc:
m = 11 ** n
row.append(m)
n += 1
for i in range(0, len(row)):
row[i] = ' '.join(list(str(row[i])))
for i in range(0, len(row)):
row[i] = row[i].center(len(row[-1]),' ')
result = '\n'.join(row)
print(result)
输出:
Input number of rows: 4
1
1 1
1 2 1
1 3 3 1
一个简短的版本是:
inc = int(input('Input number of rows: '))
max_len = 2 * len(str(11**inc)) - 1
row = (' '.join([*str(11**p)]).center(max_len,' ') for p in range(inc))
print(*row, sep='\n')
输出:
Input number of rows: 4
1
1 1
1 2 1
1 3 3 1
答案 1 :(得分:1)
您可以通过len(row) - i
缩进每一行,然后将每个字符隔开,以使每一行的长度加倍,以平衡本应正确的对齐方式。
inc = int(input('Input number of rows: '))
n = 0
row = []
while n <= inc:
m = 11 ** n
row.append(m)
n += 1
for i in range(0, len(row)):
indent = " " * (len(row) - i)
spaced_row = " ".join(list(str(row[i])))
row[i] = indent + spaced_row
result = '\n'.join(row)
print(result)
输出
Input number of rows: 3
1
1 1
1 2 1
1 3 3 1
答案 2 :(得分:1)
这更简单:
ROWS = 5
def row( a, b ) :
return ' ' * (b-a-1) + ' '.join([i for i in str(11**a)])
for i in range(ROWS) :
print row( i, ROWS )
输出:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
,如果要在python3中使用,请在print( .. )
调用中添加括号。