Pascal's Triangle for Python

后端 未结 11 1562
轮回少年
轮回少年 2020-11-30 06:13

As a learning experience for Python, I am trying to code my own version of Pascal\'s triangle. It took me a few hours (as I am just starting), but I came out with this code:

11条回答
  •  生来不讨喜
    2020-11-30 06:44

    Here is my attempt:

    def generate_pascal_triangle(rows):
        if rows == 1: return [[1]]
    
        triangle = [[1], [1, 1]] # pre-populate with the first two rows
    
        row = [1, 1] # Starts with the second row and calculate the next
    
        for i in range(2, rows):
            row = [1] + [sum(column) for column in zip(row[1:], row)] + [1]
            triangle.append(row)
    
        return triangle
    
    for row in generate_pascal_triangle(6):
        print row
    

    Discussion

    • The first two rows of the triangle is hard-coded
    • The zip() call basically pairs two adjacent numbers together
    • We still have to add 1 to the beginning and another 1 to the end because the zip() call only generates the middle of the next row

提交回复
热议问题