Pascal's Triangle for Python

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

    # call the function ! Indent properly , everything should be inside the function
    def triangle():
    
              matrix=[[0 for i in range(0,20)]for e in range(0,10)]         # This method assigns 0's to all Rows and Columns , the range is mentioned
              div=20/2           # it give us the most middle columns 
              matrix[0][div]=1        # assigning 1 to the middle of first row 
              for i in range(1,len(matrix)-1): # it goes column by column
                   for j in range(1,20-1):  #  this loop goes row by row
                       matrix[i][j]=matrix[i-1][j-1]+matrix[i-1][j+1]               # this is the formula , first element of the matrix gets , addition of i index (which is 0 at first ) with third value on the the related row
        # replacing 0s with spaces :) 
              for i in range(0,len(matrix)):
                  for j in range(0,20):
                       if matrix[i][j]==0:       #  Replacing 0's with spaces
                            matrix[i][j]=" "
    
              for i in range(0,len(matrix)-1):           # using spaces , the triangle will printed beautifully 
                    for j in range(0,20):
                        print 1*" ",matrix[i][j],1*" ", # giving some spaces in two sides of the printing numbers
    triangle() # calling the function
    

    would print something like this

                           1
                    1              1
               1           2            1
          1         3            3            1
      1        4        6            4               1
    

提交回复
热议问题