Don Marko - 11 months ago 79

Python Question

So I'm making a Pascal's triangle and I can't figure out why this code isn't working. It prints out something like this

`[]`

[1]

[1, 2]

[1, 3, 3]

[1, 4, 6, 4]

[1, 5, 10, 10, 5]

[1, 6, 15, 20, 15, 6]

[1, 7, 21, 35, 35, 21, 7]

[1, 8, 28, 56, 70, 56, 28, 8]

[1, 9, 36, 84, 126, 126, 84, 36, 9]

Which is almost correct, however it seems that the values seem to be the row number too high, so 1,2 , If you count 2 as the first row and 1 as the 0th row, 2 is 1 value too high since it is in the first row, it should be 1,1. The next row should be 1,2,1, the first value is correct but the next one is 1 value too high and the one after that is 2 values too high.

I tried doing something like append(a-i) but it doesn't seem to work, how would you get this to print correctly?

`def triangle(rows):`

for rownum in range (rows):

newValue=1

PrintingList = list()

for iteration in range (rownum):

newValue = newValue * ( rownum-iteration ) * 1 / ( iteration + 1 )

PrintingList.append(int(newValue))

print(PrintingList)

print()

Thanks in advance.

Answer Source

I would change `PrintingList = list()`

to `PrintingList = [newValue]`

.

`triangle(10)`

then gives you the following:

```
[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]
```

Which is a valid Pascal's triangle.