递归帕斯卡三角形布局 [英] Recursive Pascals Triangle Layout
问题描述
所以我设法使Pascals Triangle能够成功打印出打印的数字,但是,我无法使用以下方式获得正确的格式设置:
So i've managed to get Pascals Triangle to print successfully in terms of what numbers are printed, however, i can't get the formatting correct using:
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]
这是正确的,但是我希望将其格式化为直角三角形,例如:
which is correct, however i want it to be formatted as a right angle triangle such as:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
我的问题是,我是这种语言的新手,无法确定将拆分等内容放置在代码中的位置,以便能够按此方式进行打印. 朝正确方向的任何帮助或推动将不胜感激. 谢谢.
my issue is, i'm new to this language and cannot work out where to put the splits and such in my code to be able to get it to print as this. Any help or nudge in the right direction would be very much appreciated. Thanks.
推荐答案
您要使用str.join()
函数,该函数会打印出由字符串分隔的列表中的所有元素:
You want to use the str.join()
function, which prints out all elements in a list separated by a string:
>>> L = printPascal(6)
>>> for row in L:
... print ' '.join(map(str, row))
...
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
' '.join(list)
表示您要打印出用空格(' '
)分隔的列表中的每个元素.
' '.join(list)
means you're printing out every element in a list separated by a space (' '
).
但是,列表中的每个元素都必须是一个字符串,以使join
函数起作用.你是整数.为了解决这个问题,我通过执行map(str, row)
将所有整数更改为字符串.这等效于:
However, every element in the list needs to be a string in order for the join
function to work. Yours are integers. To fix this, I've changed all the integers to strings by doing map(str, row)
. This is equivalent to:
new_list = []
for item in row:
new_list.append(str(item))
或作为列表理解:
[str(item) for item in row]
这篇关于递归帕斯卡三角形布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!