USE!!! PYTHON!!! Pascal\'s triangle is an infinite two-dimensional pattern of nu
ID: 3668122 • Letter: U
Question
USE!!! PYTHON!!!
Pascal's triangle is an infinite two-dimensional pattern of numbers whose first six lines are:
usual formatting:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
alternate formatting (may be helpful for code):
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
The first line, line 0, contains just 1. All other lines start and end with a 1 as well. The other numbers in those lines are obtained using the following rule: the number at position i is the sum of the numbers in position i-1 and i in the previous line. Implement a recursive function pascalLine takes as a parameter a non-negative integer n and returns a list containing the sequence of numbers appearing in the nth line of Pascal's Triangle. The function will have one loop in it to construct the list corresponding to the line returned, but the rest of the work should be done recursively. The following shows some sample runs of the function:
>>> pascalLine(0)
[1]
>>> pascalLine(1)
[1, 1]
>>> pascalLine(2)
[1, 2, 1]
>>> pascalLine(3)
[1, 3, 3, 1]
>>> pascalLine(4)
[1, 4, 6, 4, 1]
>>> pascalLine(7)
[1, 7, 21, 35, 35, 21, 7, 1]
usual formatting:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
alternate formatting (may be helpful for code):
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Explanation / Answer
PYTHON Program:
import math
def pascals_triangle(n_rows):
results = [ ]
for _ in range(n_rows):
row = [1]
if results:
last_row = results[-1]
row.extend([sum(pair) for pair in zip(last_row, last_row[1:])])
row.append(1)
results.append(row) # add the row to the results.
return results
for i in pascals_triangle(8):
print(i)
here the above code for the alternate formatting of the given triangle. The below code for the usual formating code for the above triangle as follows:
Program:
def printTrg(rows):
r1 = [1]
r2 = [1, 1]
trg = [r1, r2]
r = [ ]
if rows == 1:
r1[0] = str(r1[0])
print(' '.join(r1))
elif rows == 2:
for o in trg:
for a in range(len(o)):
o[a] = str(o[a])
print((' ')*(2-(a+1)), (' '.join(o)))
else:
for i in range(2, rows):
trg.append([1]*i)
for n in range(1, i):
trg[i][n] = (trg[i-1][n-1]+trg[i-1][n])
trg[i].append(1)
for x in range(len(trg)):
for y in trg[x]:
s = str(y)
r.append(s)
print((' ')*(rows-(x+1)), (' ' .join(r)))
r = [ ]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.