299. Python Program to Print a Zigzag Pattern
HardPhase 3 · Challenge
This takes a few steps, and you know every tool it needs: nested for loops, if and the % sign. Draw the first 8 columns on squared paper first.
Overview
A zigzag goes up and down again and again. The trick is to find the rule that repeats, and % is the tool for anything that repeats.
Problem Statement
Thabo draws a wave for the title screen of a boat game. Read a whole number n, the width. Print 3 rows of n characters. Number the columns from 0 to n - 1.
Each column has exactly one star. Its row depends on the column number divided by 4: look at the remainder, col % 4.
- Remainder 0: the star is in the bottom row.
- Remainder 1: the star is in the middle row.
- Remainder 2: the star is in the top row.
- Remainder 3: the star is in the middle row.
Every other place is a space. So the line starts at the bottom, climbs to the top, comes back down, and starts again every 4 columns.
Examples
Example 1. Input 9 gives:
* *
* * * *
* * *
Why: column 0 has its star at the bottom, column 1 in the middle, column 2 at the top and column 3 in the middle. Columns 4 to 7 repeat this, and column 8 is at the bottom again.
Example 2. Input 5 gives:
*
* *
* *
Why: the top row has a star only in column 2. The middle row has stars in columns 1 and 3. The bottom row has stars in columns 0 and 4.
Input
One whole number n, the width (3 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
Exactly 3 lines: the top row, the middle row and the bottom row. The spaces at the start of a line matter: the tests check them. A space at the end of a line is fine: the tests ignore it. The tests try 7 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.