Home > Back-end >  Pascal's triangle in python issue
Pascal's triangle in python issue

Time:11-13

I'm trying to create a pascal's triangle generator, but for some reason it's not giving me the correct output. I should get:

[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]

But instead I'm getting:

[1, 1]
[1, 2, 1]
[1, 3, 4, 1]
[1, 4, 8, 9, 1]

Here's the code:

length = 4

lst = [1]

for i in range(length):
    for j in range(i):
        lst[j 1] = temp[j]  temp[j 1]
    lst.append(1)
    temp = lst
    print(lst)

I've been looking at it for hours and I couldn't spot anything wrong with it. I even wrote down the first couple of iterations on paper and it all seems just fine. But somehow it's still not working? It might be me being blind again but I've really got no clue.

I'm so confused, why is it adding the entries from the current list when I created a temporary list to get values from?

CodePudding user response:

There should be a line added that clones the list since right now you are only referencing it.

length = 4

lst = [1]

for i in range(length):
    temp = list(lst)
    for j in range(i):
        lst[j 1] = temp[j]  temp[j 1]
    lst.append(1)
    temp = lst
    print(lst)

This produces correct output

CodePudding user response:

If you change temp = list to temp = list.copy(), your code will produce the expected result.

If all you want is to obtain pascal's triangle "n" rows long, you might be interested to know that Scipy offers you a function to do this.

from scipy.linalg import pascal

print (pascal(5, kind = 'lower'))

# result:
    # [[1 0 0 0 0]
    #  [1 1 0 0 0]    
    #  [1 2 1 0 0]
    #  [1 3 3 1 0]
    #  [1 4 6 4 1]]

If you're trying to return quite a large number of rows, this approach (as opposed to the for loop approach you've tried) might be more efficient.

  • Related