Pascal's Triangle for Python

后端 未结 11 1563
轮回少年
轮回少年 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:53

    Here is a simple way of implementing the pascal triangle:

    def pascal_triangle(n):
        myList = []
        trow = [1]
        y = [0]
        for x in range(max(n,0)):
            myList.append(trow)
            trow=[l+r for l,r in zip(trow+y, y+trow)]
    
        for item in myList:
            print(item)
    
    pascal_triangle(5)
    

    Python zip() function returns the zip object, which is the iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together. Python zip is the container that holds real data inside.

    Python zip() function takes iterables (can be zero or more), makes an iterator that aggregates items based on the iterables passed, and returns the iterator of tuples.

提交回复
热议问题