280. Python Program to Print a 0 and 1 Triangle
EasyPhase 1 · Warm-up
Nested for loops, if and % are all you need, and you know each of them.
Overview
Computers store everything as 0s and 1s. In this pattern, 1 and 0 take turns, and you use % to choose which one comes next.
Problem Statement
Noah plans a string of party lights. 1 means a light is on, and 0 means it is off. Read a whole number n and print n rows:
- Row
ihasinumbers. - Every row starts with 1. Then 0 and 1 take turns: 1, 0, 1, 0 and so on.
- Put one space between the numbers.
Steps
- Read
nand turn it into a whole number. - Loop over the rows, from 1 to
n. - In each row, loop over the places, from 1 to the row number.
- Print 1 at an odd place and 0 at an even place, on the same line.
- End the line after each row.
Examples
Example 1. Input 4 gives:
1
1 0
1 0 1
1 0 1 0
Why: each row starts with 1, and the numbers take turns. Row 4 has 4 numbers.
Example 2. Input 2 gives:
1
1 0
Why: row 1 has one 1. Row 2 has a 1 and then a 0.
Input
One whole number n (1 or more). 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. Line i holds i numbers, with one space between them. Every line starts at the left edge, with no space in front. A space at the end of a line is fine: the tests ignore it. The tests try 5 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.