290. Python Program to Print an Hourglass of Stars
MediumPhase 2 · Practice
This one takes a few steps, but you know every tool it uses: two for loops, range() that counts down, and how * repeats text.
Overview
An hourglass is an upside-down pyramid with a normal pyramid below it. The hard part is to join them so that the thin middle appears only once.
Problem Statement
Amara draws a sand timer for a cooking app. A sand timer, or hourglass, is wide at the top and the bottom and thin in the middle. Read a whole number n. It is the number of rows in the top half, and the middle row with 1 star belongs to the top half.
- Row 1 has no spaces and
2 * n - 1stars. - Each row of the top half has 1 space more and 2 stars less, down to the middle row:
n - 1spaces and 1 star. Print the middle row only once. - The bottom half gets wider again: 3 stars, then 5, and so on, up to
2 * n - 1stars. Each of these rows has 1 space less than the row above it.
So the hourglass 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 5, 3 and 1 stars. The bottom half grows back to 3 and 5 stars. The row with 1 star is printed once.
Example 2. Input 2 gives:
***
*
***
Why: the top half has 3 stars, then 1 space and 1 star. The bottom half has just 1 row, with 3 stars.
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 hourglass 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.