Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

So I've been dealing with a pascal triangle however I'm attempting to make labels on each row that say something like Row=0, Row=1, Row=2. I'm attempting to labels before each new row begins the Pascal triangle. Would someone be able to help me make it dependent on this code? Much appreciated.

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

1 Answer

0 votes
by (26.4k points)

Above all else, kindly try not to utilize names of built-in functions as variable names (for your situation, list; I've transformed it to l). Besides that, putting a label as you referenced is basically referring to the iteration of the peripheral loop you have. This after code ought to carry on as expected:

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

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]

Looking for a good python tutorial course? Join the python certification course and get certified.

For more details, do check out the below video tutorial...

Browse Categories

...