Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The goal of this project is to gain more practice with List. In Python, the List

ID: 674618 • Letter: T

Question

The goal of this project is to gain more practice with List. In Python, the List type is a container that holds a number of other objects, in a given order. This data structure is so useful and powerful that you can find it in almost every algorithm. In this project, we want to generate a Pascal’s triangle. The figure below is a simple Pascal’s triangle whose height is 7.   

1

1 1

1 2 1

1 3 3 1

1 4 6 4 1

1 5 10 10 5 1

1 6 15 20 15 6 1

Project Specification

1. Your program will ask the user to input a positive number that will be used as the height of triangle. Check for this condition.

2. To generate the triangle, you start from the first row, which is always 1, and the second row which is always 1 1. 3. After the first two rows, each row at level his generated from the values at row h-1. Note that the leftmost number and the rightmost number in any row are always 1. Note that, in row h, there are h numbers.

4. We will use a list to represent a row. Because the triangle consists of multiple rows, we will require another list to hold all the lists that makes the triangle rows. Thus, we will have a list of lists.

5. You should include specifications of the function. (Preconditions and Postconditions)

6. You should also write test cases for this program.

7. You should use assert statements in your code.

8. You should test your method thoroughly. The given figure is in shape of an equilateral triangle not a right angle triangle. Hence, consider it as an equilateral triangle.

Explanation / Answer

def generate_pascal_triangle(rows):
if rows == 1: return [[1]]

triangle = [[1 ], [1, 1]] #base cases with first two rows

row = [1, 1] # intitilisation of next rows

for i in range(2, rows):
row = [1] + [sum(column) for column in zip(row[1:], row)] + [1]# calculation of nect rows
triangle.append(row)

return triangle
n = int(input('Enter a positive number'))
assert (n > 0),"Should enter a positive number!"
for row in generate_pascal_triangle(n):
nvals = len(row)
spaces = (80 - 5 * nvals)/2
paddington = " " * spaces
bear = ""
for val in row:
bear += "%5x" % val
print paddington + bear

test cases:

run the program for values : -1, 0, 1 , 2, 3 7

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote