286. Python Program to Print a Diamond of Stars
MediumPhase 2 · Practice
This takes a few steps and some planning, but every tool is one you know: two for loops, a range() that counts down, and * to repeat text.
Overview
A diamond is two star pyramids, one on top of the other. The hard part is to join them so that the widest row appears only once.
Problem Statement
Elena draws a gem for a treasure game. Read a whole number n. It is the number of rows in the top half of the diamond, and the widest row belongs to the top half.
- The top half is a star pyramid of
nrows. Rowihasn - ispaces and then2 * i - 1stars, forifrom 1 ton. - The widest row, in the middle, has
2 * n - 1stars. Print it only once. - The bottom half gets narrower again: first
2 * n - 3stars, then 2 stars less in each row, down to 1 star. Each of these rows has 1 space more than the row above it.
So the diamond has 2 * n - 1 rows. The stars touch: there are no spaces between them.
Examples
Example 1. Input 3 gives:
*
***
*****
***
*
Why: the top half has 3 rows, with 1, 3 and 5 stars. The bottom half goes back down to 3 stars and 1 star. The row with 5 stars is printed once.
Example 2. Input 2 gives:
*
***
*
Why: the top half has 2 rows, with 1 and 3 stars. The bottom half has just 1 row, with 1 space and 1 star.
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
2 * n - 1 lines. For n = 1, the diamond is a single star. The spaces at the start of a line matter: the tests check them. The tests try 6 different inputs.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.