livepython.net

298. Python Program to Print a Hollow Diamond

HardPhase 3 · Challenge

This one takes a few steps, but you know every tool it uses: for loops, if and how * repeats text. Draw a small diamond on paper first and count the spaces in each row.

Overview

A hollow shape keeps only its edges. Here you take the diamond of stars and print only its outline, so every row needs two kinds of spaces: the ones in front and the ones inside.

Problem Statement

Imani draws the frame of a kite for a game about a windy day. 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 diamond has 2 * n - 1 rows in all.

Think of the full diamond of stars. Row i of its top half has n - i spaces and then 2 * i - 1 stars. The bottom half is the top half upside down, without the widest row. The hollow diamond keeps only the outline:

  • A row with 1 star stays as it is: n - 1 spaces, then 1 star. These are the top row and the bottom row.
  • In every other row, keep the first and the last star. The stars between them become spaces. So the row is n - i spaces, a star, 2 * i - 3 spaces and a star.

Examples

Example 1. Input 3 gives:

  *
 * *
*   *
 * *
  *

Why: the widest row of the full diamond has 5 stars. Its outline is a star, 3 spaces and a star. The rows above and below it have 1 space inside, and the top and bottom rows are a single star.

Example 2. Input 4 gives:

   *
  * *
 *   *
*     *
 *   *
  * *
   *

Why: the top half has 4 rows. The widest row has a star, 5 spaces and a star, because 2 * 4 - 3 is 5. It is printed only once, and the bottom half goes back up to a single 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. 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.

Finish this chapter firstChapter 10 · For Loops
solution.py
# write your code here

EXPECTED OUTPUT

1 *
2 * *
3* *
4 * *
5 *

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.