Recursive Pascals Triangle Layout

三世轮回 提交于 2020-01-15 09:30:29

问题


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))

this prints as:

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.


回答1:


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) means you're printing out every element in a list separated by a space (' ').

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))

Or as a list comprehension:

[str(item) for item in row]


来源:https://stackoverflow.com/questions/36911552/recursive-pascals-triangle-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!