292. Python Program to Print an X Pattern
MediumPhase 2 · Practice
This one takes a few steps, but you know every tool it uses: nested for loops, if with or, and how to build a string with +=.
Overview
Some patterns are easier to see as a grid. You check every place in the grid and use a rule to decide if it gets a star.
Problem Statement
Kenji marks the spot on a treasure map with a big X. Read a whole number n and print a grid of n rows and n columns. Count the rows and the columns from 1.
- A place gets a star when its row number equals its column number. These stars make the line from the top left to the bottom right.
- A place also gets a star when its row number plus its column number equals
n + 1. These stars make the line from the top right to the bottom left. - Every other place is a space.
Each place is one character, and there are no extra spaces between places. n is odd, so the two lines cross in one star in the middle.
Examples
Example 1. Input 5 gives:
* *
* *
*
* *
* *
Why: in row 2, column 2 gets a star, because 2 equals 2. Column 4 gets a star too, because 2 + 4 = 6, which is 5 + 1. Row 3 has one star, in column 3, where the two lines cross.
Example 2. Input 3 gives:
* *
*
* *
Why: row 1 has stars in columns 1 and 3, with one space between them. Row 2 has one space and then a star in column 2.
Input
One odd whole number n, 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
n lines. The spaces before a star and between two stars matter: the tests check them. 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.