0

why the while loop is executing more times than expected in printing a pascal triangle? every time the while loop is executed x is incremented by 1 whereas n remains the same I just started learning python please help

memo = {0:1}
def fac(n):
    if n not in memo:
        memo[n] = n*fac(n-1)
        return memo[n]
    else:
        return memo[n]

def pascal(x, space):
    while(x <= n):
        for j in range(space):
            print(" ", end = "")
        for i in range(0, x+1):
            print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
        print("\n", end = "")
        x += 1
        space -= 1
        pascal(x, space)

n = eval(input())
space = n
x = 0
pascal(x, space)
anonymous
  • 141
  • 2
  • 14

1 Answers1

0

You are using two methods to iterate through the numbers in the pascal function, a while loop, and a recursive call. You just need one of them.

Keeping the while loop:

def pascal(x, space):
    while(x <= n):
        for j in range(space):
            print(" ", end = "")
        for i in range(0, x+1):
            print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
        print("\n", end = "")
        x += 1
        space -= 1

Keeping the recursive call, turning the while into an if:

def pascal(x, space):
    if(x <= n):
        for j in range(space):
            print(" ", end = "")
        for i in range(0, x+1):
            print ( int(fac(x)/(fac(i)*fac(x-i))), end = " " )
        print("\n", end = "")
        x += 1
        space -= 1
        pascal(x, space)

Given 3 as input, both versions print the following:

   1
  1 1
 1 2 1
1 3 3 1
legoscia
  • 39,593
  • 22
  • 116
  • 167