Search code examples
pythonpython-3.xpascals-triangle

TypeError: 'int' object is not subscriptable - Python3


I am trying to solve the Pascal's triangle problem in python3 but keep getting TypeError 'int' object is not subscriptable everytime.

Here, the question is: Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        pascal = []

        for i in range(numRows):
            pascal.append([])
            for j in range(i+1):
                if j == 0 or j == i:
                    pascal.append(1)
                else:
                    pascal[i].append(pascal[i - 1][j - 1] + pascal[i - 1][j])
        return pascal

Solution

  • This line is incorrect:

    pascal.append(1)
    

    it should be:

    pascal[i].append(1)
    

    Otherwise the next row you compute tries to index 1[j - 1]. Once fixed, for an argument of 10, I get the return value

    [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1],
    [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1],
    [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1],
    [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]]