Pascal's Triangle for Python

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

    Beginner Python student here. Here's my attempt at it, a very literal approach, using two For loops:

    pascal = [[1]]
    num = int(input("Number of iterations: "))
    print(pascal[0]) # the very first row
    for i in range(1,num+1):
        pascal.append([1]) # start off with 1
        for j in range(len(pascal[i-1])-1):
        # the number of times we need to run this loop is (# of elements in the row above)-1
            pascal[i].append(pascal[i-1][j]+pascal[i-1][j+1])
            # add two adjacent numbers of the row above together
        pascal[i].append(1) # and cap it with 1
        print(pascal[i])
    

提交回复
热议问题