Search code examples
pythonpascals-triangle

Print Pascal's Triangle using only limited programming concepts


Please tell me what is wrong with my program. I want to print Pascal's Triangle using only nested loops and if statements because these have been covered in our course:

x=int(input("Enter depth of triangle "))
y=0
n=1
while(y<=x):
    a=11**y
    z=a
    za=0
    b=z%10
    z=z//10
    if(y==0):
        print(x*" ",b)
    elif(y!=0):
        if(za==0):
            print(x*" ",b,end="")
        elif(za<x):
            print((x-za)*" ",b,end=" ")
        elif(za==x):
            print((x-za)*" ",b)
    y=y+1
    za=za+1
    else:
    print("program done")

Output:

Enter depth of triangle 4
     1
     1     1     1     1program done

Solution

  • If you read the Calculating a row or diagonal by itself section of the Wikipedia article on Pascal's Triangle, getting the numbers just using nested while loops (no ifs) seems fairly straight forward:

    depth = int(input("Enter depth of triangle: "))
    
    row = 0
    
    while row < depth:
        number = 1
        denominator = 1
        numerator = row
    
        print(number, end=' ')
    
        while numerator > 0:
            number = number * numerator // denominator
            print(number, end=' ')
            numerator = numerator - 1
            denominator = denominator + 1
    
        print()
        row = row + 1
    

    OUTPUT

    > python3 test.py
    Enter depth of triangle: 10
    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 
    >
    

    Now add the necessary code to reshape the output from a right triange into more of an isosceles triangle.

    Please tell me what is wrong with my program.

    You say that you want to solve the problem using nested loops but you don't actually have nested loops -- just a single outer loop. Going from rows of the triangle to powers of 11 is simple, given some addition carry logic, but going the other way 'round seems a difficult way to go about this:

    a=11**y
    

    And you should pick better variable names.