livepython.net

291. Python Program to Print a Butterfly Pattern

MediumPhase 2 · Practice

This takes a few steps: plan the three parts of a row first. You know every tool it needs: two for loops, a range() that counts down, and * to repeat text.

Overview

The butterfly is a classic pattern question. Each row has two parts of stars with a gap between them, and you have to get the size of the gap right.

Problem Statement

Sofia draws a butterfly for a garden poster. Read a whole number n and print the butterfly:

  • The top half has n rows. Row i has i stars, then 2 * (n - i) spaces, then i stars.
  • So in each new row, both wings get 1 star more, and the gap gets 2 spaces smaller.
  • Row n has no gap: it is 2 * n stars in a row. It is the middle row of the butterfly, and it appears only once.
  • The bottom half repeats the top half in reverse order, but it starts one row lower, at row n - 1. So it prints rows n - 1, n - 2 and so on, down to row 1.

So the butterfly has 2 * n - 1 rows. No row has spaces in front of its first star.

Examples

Example 1. Input 3 gives:

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

Why: row 1 has 1 star, 4 spaces and 1 star, because 2 * (3 - 1) is 4. Row 3 has no gap, so it is 6 stars, printed once. Then rows 2 and 1 come again.

Example 2. Input 2 gives:

*  *
****
*  *

Why: row 1 has 1 star, 2 spaces and 1 star. Row 2 is 4 stars, printed once. Then row 1 comes again.

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 butterfly is one row: **. The spaces in the middle 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.

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.