Solution Review: Pascal's Triangle

This review provides a detailed analysis of the solution to Pascal's Triangle problem.

We'll cover the following

Solution: Using Recursion

Press + to interact
def printPascal(testVariable) :
# Base Case
if testVariable == 0 :
return [1]
else :
line = [1]
# Recursive Case
previousLine = printPascal(testVariable - 1)
for i in range(len(previousLine) - 1):
line.append(previousLine[i] + previousLine[i + 1])
line += [1]
return line
# Driver Code
testVariable = 5
print(printPascal(testVariable))

Explanation:

In the code snippet above, we use the values of the previous function call to calculate the values of the current function call. If we reach 0th0th row, we return a list containing only 11 value: [1][1]. This is our base case.

Now, for each recursive call, we use the values of the previous solution. Let’s have a look at the sequence of function calls:

Let’s also have a look at the recursive case in detail:

line = [1]
previousLine = printPascal(testVariable - 1)
for i in range(len(previousLine) - 1):
   line.append(previousLine[i] + previousLine[i + 1])
line += [1]

We are going to analyze this loop for the part when the child function call - printPascal(4) has returned the value to the parent function call - printPascal(5) and is stored in the variable previousLine.


Let’s try another challenge in the next lesson.