Search⌘ K

Solution Review: Pascal's Triangle

Explore how to implement Pascal's Triangle using recursion by understanding the base case and the recursive construction of each row from the previous one. This lesson helps you grasp how recursive calls work together to build the triangle.

We'll cover the following...

Solution: Using Recursion

Python 3.5
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 the 0th0th ...