Geometric shapes · 2 / 13 Theory

How to think about a shape: the formula for each row

Triangles and pyramids look hard, but they have a trick: in each row there is a number of spaces and a number of symbols that can be calculated from the row number. You only have to find the formula.

A three-step method

  • Draw the shape by hand for a small size (for example, 4).
  • Make a table with the row number (starting at 0), the spaces and the symbols of that row.
  • Look for the relationship between row and amount: it is usually row, width - row, width - 1 - row or 2 * row + 1.

Example 1: a staircase to the right

For width 4, each row starts with one more space and has one symbol fewer than the previous one on the right side:

RowSpacesSymbols
004
113
222
331

Spaces = row and symbols = width - row:

width = 4
for row in range(width):
    print(" " * row + "#" * (width - row))
# ####
#  ###
#   ##
#    #

Removing the spaces (" " * row) would leave a triangle stuck to the left, and with row + 1 symbols instead of width - row, a growing one. Notice that only the formulas change: the structure of the loop is always the same. This reasoning works for Triangle Rectangle and Triangle Rectangle Mirror.

Example 2: a centered pyramid of symbols

In a pyramid, each row has 2 more symbols than the previous one (1, 3, 5, 7…) and is centered, so the spaces on the left decrease one by one. For height 4:

RowSpacesSymbols
031
123
215
307

Spaces = height - 1 - row and symbols = 2 * row + 1:

height = 4
for row in range(height):
    print(" " * (height - 1 - row) + "*" * (2 * row + 1))
#    *
#   ***
#  *****
# *******

When the row is cut from a text

In some shapes you do not repeat a symbol, but each row is a piece of a word. In Triangle Rectangle String and Draw a pyramid slicing is used:

text = "python"
for n in range(1, len(text) + 1):
    print(text[:n])
# p
# py
# pyt
# pyth
# pytho
# python

With text[-n:] the piece is taken from the end, and with text[a:b] you can take the letters around the center: only the part of the text shown in each row changes.

Parallelogram

It is a rectangle whose rows shift one more space each time: spaces = row, symbols = width, as in the last example of the previous article.

Check your formula

Before considering the exercise done, test the smallest case (width = 1) and an odd and an even size. Mistakes are usually in the first and last rows (when a formula should be 0 or 1 and it is something else).