Search code examples
pythonpython-3.xpascals-triangle

Pascal Triangle Python


So I've been working on a pascal triangle but I'm trying to make labels on each row that say something like Row=0, Row=1, Row=2. I'm trying to place these labels before each new row starts on the Pascal triangle. Can someone help me make it based off of this code? Thanks.

x = int(input("Enter the desired height. "))
list=[1]
for i in range(x):
    print(list)
    newlist=[]
    newlist.append(list[0])
    for i in range(len(list)-1):
        newlist.append(list[i]+list[i+1])
    newlist.append(list[-1])
    list=newlist

Solution

  • First of all, please avoid using names of built-in functions as variable names (in your case, list; I've changed it to l). Aside from that, placing a label as you mentioned is simply referring to the iteration of the outermost loop you have. This following code should behave as intended:

    x = int(input("Enter the desired height. "))
    l = [1]
    for i in range(x):
        # Modified v
        print("Row", i + 1, l)
        newlist = []
        newlist.append(l[0])
        for i in range(len(l) - 1):
            newlist.append(l[i] + l[i+1])
        newlist.append(l[-1])
        l = newlist
    

    Here's a sample run:

    Enter the desired height. 4
    Row 1 [1]
    Row 2 [1, 1]
    Row 3 [1, 2, 1]
    Row 4 [1, 3, 3, 1]
    

    Hope this helped!