Home > database >  Extra zeros appear at the end of existing items when appending new lists to a list
Extra zeros appear at the end of existing items when appending new lists to a list

Time:06-23

I'm trying to solve Pascal triangle prblem on leetcode: "Return a given number of Pascal triangle rows". I've defined a function getNextRow(row) that calculates the next rows given the current one and then calling it a certain number of times and appending these rows to my resulting list. For some reason extra zero appears at the end of the previous row each time I'm adding a new row.

E.g. Input: 5 #5 rows needed

Output: [[1,0],[1,1,0],[1,2,1,0],[1,3,3,1,0],[1,4,6,4,1]]

Expected output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

def getNextRow(row):
    res = [1]
    if len(row) == 0:
        return res
    row.append(0)
    for i in range(len(row) - 1):
        res.append(row[i]   row[i 1])
    return res


def generate(numRows):
    pascal = [] #Empty resulting triangle
    currentRow = []
    num = 0 #Counter
    while num < numRows:
        currentRow = getNextRow(currentRow)
        pascal.append(currentRow)
        num  = 1
    return pascal
                
if __name__ == '__main__':
    print(generate(5))

CodePudding user response:

The issue here is because you are reusing the variable currentRow on each iteration. In the fourth line of the getNextRow function, you are appending 0 to the row passed in to the variable. This is directly referencing the currentRow variable in memory and therefore making changes before the currentRow is added to the pascal list. To fix this, you can either copy the currentRow before you add it to the pascal list e.g:

pascal.append(currentRow.copy())

or copy the row variable within getNextRow like so:

def getNextRow(row):
    row = row.copy()

Hope this helps!

CodePudding user response:

You append zero to row in getNextRow(). That entry in the list never gets modified so you'll always see a redundant trailing zero.

Your code is also rather cumbersome. Here's a more concise implementation:-

def pascal(n):
    r = [[1]]
    for i in range(2, n 1):
        p = r[-1]
        r.append([1]   [p[j-1]   p[j] for j in range(1, i-1)]   [1])
    return r

print(pascal(6))

Output:

[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
  • Related