Use python to write a function that will generate the ith row of pascal’s triangle (using recursion)
The method signature should be pascal(row). It should return a list of elements that would be in that row of Pascal’s Triangle. For example the 0th row is [1] and the 2nd row is [1,2,1]
Solution:
Recursive function to generate ith row of pascal's triangle:
#Function to return nth pascal row
def pascal(row):
pascalrow=[]
#First element in row is always 1
pascalrow.append(1);
#If the row is 0
if(row==0):
return pascalrow
#Generating previous row
previousrow=pascal(row-1)
for i in range(1,len(previousrow)):
#Generating urrent row by using previous row
current=previousrow[i-1]+previousrow[i];
pascalrow.append(current)
#last element is always 1
pascalrow.append(1)
#returning the nth pascalrow
return pascalrow
Output by calling function in python command shell:
Get Answers For Free
Most questions answered within 1 hours.