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
def printPascal(testVariable) :# Base Caseif testVariable == 0 :return [1]else :line = [1]# Recursive CasepreviousLine = printPascal(testVariable - 1)for i in range(len(previousLine) - 1):line.append(previousLine[i] + previousLine[i + 1])line += [1]return line# Driver CodetestVariable = 5print(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 row, we return a list containing only value: . 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.