livepython.net

289. Python Program to Print Pascal's Triangle

MediumPhase 2 · Practice

It takes a few steps, but the tools are ones you know: a list with append(), nested for loops and print() with end.

Overview

Pascal's triangle is a famous number triangle, named after Blaise Pascal, a French mathematician. It is a common question, because each row is built from the row before it.

Problem Statement

Tariq's maths club prints Pascal's triangle on a poster. Read a whole number n and print the first n rows:

  • Row 1 is 1.
  • Every row has one number more than the row above it.
  • Every row starts with 1 and ends with 1.
  • Every other number is the sum of two numbers in the row above: the one in the same place, and the one just before it.

For example, row 4 is 1 3 3 1. So row 5 is 1, then 1 + 3 = 4, 3 + 3 = 6, 3 + 1 = 4, and then 1.

Print each row on its own line, with one space between the numbers. Do not centre the rows: every row starts at the left edge, with no spaces in front.

Examples

Example 1. Input 5 gives:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Why: the middle numbers of row 5 are 1 + 3 = 4, 3 + 3 = 6 and 3 + 1 = 4, from the row above. The 1 at each end stays 1.

Example 2. Input 3 gives:

1
1 1
1 2 1

Why: row 3 has three numbers. The ends are 1, and the middle number is 1 + 1 = 2.

Input

One whole number n, from 1 to 15. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

n lines of numbers, with one space between the numbers. Numbers with more digits make a row wider, and that is fine. A space at the end of a line is fine: the tests ignore it. The tests try 6 different inputs.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 10 · For Loops
solution.py
# write your code here

EXPECTED OUTPUT

11
21 1
31 2 1
41 3 3 1
51 4 6 4 1

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.