【发布时间】:2016-08-23 00:48:43
【问题描述】:
所以我已经设法让 Pascals Triangle 成功打印出打印的数字,但是,我无法使用以下方法获得正确的格式:
n = int(input("Enter value of n: "))
def printPascal(n):
if n <= 0: #must be positive int
return "N must be greater than 0"
elif n == 1: #first row is 1, so if only 1 line is wanted, output always 1
return [[1]]
else:
next_row = [1] #each line begins with 1
outcome = printPascal(n-1)
prev_row = outcome[-1]
for i in range(len(prev_row)-1): #-1 from length as using index
next_row.append(prev_row[i] + prev_row[i+1])
next_row += [1]
outcome.append(next_row) #add result of next row to outcome to print
return outcome
print(printPascal(n))
这打印为:
Enter value of n: 6
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]
这是正确的,但是我希望它被格式化为直角三角形,例如:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
我的问题是,我是这种语言的新手,无法确定在我的代码中将拆分等放在哪里,以便能够让它像这样打印。 任何朝着正确方向的帮助或推动将不胜感激。 谢谢。
【问题讨论】:
标签: python python-3.x recursion pascals-triangle