I have to write a program which generates a pascal's triangle.
The user inputs the height of the triangle and it supposed to generate one.

This is what I have so far and I don't know how you would keep
adding rows after the second one. I'm so lost :(

numStr = raw_input("Please input the height of Pascal's Triangle: ")
row = int(numStr)

tri = []

row1 = [1]
row2 = [1, 1]

tri.append(row1)
tri.append(row2)

while len(tri) < row:
    print tri
    break

Recommended Answers

All 3 Replies

updated. Not sure what I'm doing, though.

numStr = raw_input("Please input the height of Pascal's Triangle: ")
height = int(numStr)

tri = []

row1 = [1]
row2 = [1, 1]
tri.append(row1)
tri.append(row2)

while len(tri) < height:
    newRow = [1]
    oldRow = tri[-1]
    start = 0
    while start < (3-2):
        newRow.append(oldRow[start] + oldRow[1])
        start += 1
    newRow.append(1)
    

print tri

You should increment height, otherwise it's an infinite loop. In general you want to use a for() or while() loop and append to a list on each loop. Add print statements to print what you don't get (especially 'height' and 'start').

I can see two way to solve the problem
1) use two dimentional list.
2) use two one dimentional list to store current row and previous row.
(that is what you are doing.)

in your case you use only previous row to calculate current row. so in start, your previous row will be row 1 which stores only 1
and you calculate current row by using currentrow = previousrow + previous row[i-1] in a loop. (first element and last element in list are special cases.) after the loop you add currentrow to triangle list and make copy currentrow to previousrow and calculate next row.
I hope that would help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.