views:

112

answers:

2

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.

+5  A: 

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.

JAB
Thanks, this seems to have fixed the issue. Not quite familiar with the concept of lists yet, much more comfortable with arrays.
Don Marko
@Don: If you come from a Java background, then Python lists would be more like Java's `ArrayList` data structure than simple arrays. In fact, as you start getting more comfortable with Python, you might want to take a look at the concept of [generators](http://www.python.org/dev/peps/pep-0255/).
JAB
I do, thanks for the advice, didn't really think of it that way.
Don Marko
A: 

I would have a look at:

http://en.wikipedia.org/wiki/Pascal%27s_triangle#Calculating_an_individual_row_or_diagonal_by_itself

which describes how to calculate the triangle's rows, one by one.

Richard Fearn