How to print 4 triangles patterns next to each other in Python?

Asked

Viewed 1,637 times

3

I need to write a program that prints 4 triangles patterns, one next to the other, separated by three horizontal spaces, as in this image below:

inserir a descrição da imagem aqui

To solve this, I wrote the following code:

for i in range(10):
    print((i + 1) * "*")

print()

for i in range(10, -1, -1):
    print((i + 1) * "*")

print()

for i in range(9, -1, -1):
    print(f'{(i + 1) * "*" : >10}')

print()

for i in range(10):
    print(f'{(i + 1) * "*" : >10}')

The problem with this code is that it prints a triangle underneath it. How can I print them side by side?

2 answers

3

It’s very simple but I had to write everything from scratch because I couldn’t reuse your code.

What you need to do is scroll through each line of the drawing that will appear, formatting the string using spacing, and then set a spacing x in the parameter end, thus:

max_size = 10
spacing = 3

for i in range(1, max_size + 1):

    # Primeiro triângulo
    print("*" * i, end = " " * (max_size - i + spacing))

    # Segundo triângulo
    print("*" * (max_size - i + 1), end = " " * (i - 1 + spacing))

    # Terceiro triângulo
    print(" " * (i - 1) + "*" * (max_size - i + 1), end = " " * spacing)

    # Quarto triângulo
    print(" " * (max_size - i) + "*" * i)

In the code I printed each row of each triangle in the same loop defining a space of 3 characters between them. This way, they can be drawn horizontally.

Extra:

To leave identical the drawing with your image, I wrote this simple code for you to put on top of the triangles the letters (a) (b) (c) (d) formatted.

print(
    "(a)" + " " * (max_size - 3 + spacing) +
    "(b)" + " " * (max_size - 3 + spacing) +
    "(c)" + " " * (max_size - 3 + spacing) +
    "(d)" + " " * (max_size - 3 + spacing)
    )

2


You can enjoy existing options for formatting, since at bottom the problem is to align texts to the right or left, and the language already has it ready.

For example, in column "a", we have strings of one or more asterisks aligned to the left, with a maximum of 10 characters (if the string has less than 10, it is completed with spaces). This can be achieved using the format {:<10}: the < indicates left alignment, and 10 indicates full size.

For column "b", one can even use the same reasoning, and do some math to get the amount of asterisks (as did the another answer), but you can also think of another way: are strings containing zero or more spaces, aligned to the right, and if the string is not large enough, it is completed with *. This can be done with the format {:*>10}: is almost the same as the previous one, but the * specifies the character that will be used to fill the missing positions. Already the > indicates right alignment, and 10 is the total size.

For columns "c" and "d", the behavior is similar. The "c" column is the same as "b", only the spaces are aligned to the left, and the "d" column is the same as "a", only the asterisks are aligned to the right. Then it would look like this:

# recebe a quantidade de triângulos e opcionalmente um separador
def triangulos(qtd, sep='   '):
    asteriscos = '*'
    espacos = ''
    print(('{:<{n}}' * 3).format('(a)', '(b)', '(c)', '(d)', n=qtd + len(sep)))
    for _ in range(qtd):
        print('{0:<{n}}{2}{1:*>{n}}{2}{1:*<{n}}{2}{0:>{n}}'.format(asteriscos, espacos, sep, n=qtd))
        asteriscos += '*'
        espacos += ' '

triangulos(10)

The function triangulos receives the amount of triangles and optionally a separator, which will be placed between the triangles (if not indicated, will be 3 spaces).

Next I use the formats already described above. The numbers before the : indicate the parameter to be printed there (zero indicates the first value passed to format, 1 indicates the second, etc). For example, {0:<{n}} indicates that the first parameter of format (the string asteriscos) will be aligned to the left, occupying at most n positions (where n is the amount passed as parameter to the function).

For the header I used '{:<{n}}' * 3, that generates the string '{:<{n}}{:<{n}}{:<{n}}', and the size n is the number of triangles plus the size of the separator (I did not consider that the separator itself will be printed here, I just put the amount of spaces so that the header is aligned with the triangles). I put 3 and not 4, because the last string ('(d)') doesn’t need to be aligned, since there’s nothing else after it.

The exit is:

(a)          (b)          (c)          (d)          
*            **********   **********            *
**           *********     *********           **
***          ********       ********          ***
****         *******         *******         ****
*****        ******           ******        *****
******       *****             *****       ******
*******      ****               ****      *******
********     ***                 ***     ********
*********    **                   **    *********
**********   *                     *   **********

Testing with other parameters:

triangulos(5, sep=' | ')

Exit:

(a)     (b)     (c)     (d)     
*     | ***** | ***** |     *
**    | ****  |  **** |    **
***   | ***   |   *** |   ***
****  | **    |    ** |  ****
***** | *     |     * | *****

If you are using Python >= 3.6, you can use f-strings to format. It looks a little different, but the general idea is the same:

def triangulos(qtd, sep='   '):
    asteriscos = '*'
    espacos = ''
    n = qtd + len(sep)
    print(f'{"(a)":<{n}}{"(b)":<{n}}{"(c)":<{n}}(d)') # o último (d) não precisa de alinhamento
    for _ in range(qtd):
        print(f'{asteriscos:<{qtd}}{sep}{espacos:*>{qtd}}{sep}{espacos:*<{qtd}}{sep}{asteriscos:>{qtd}}')
        asteriscos += '*'
        espacos += ' '

Browser other questions tagged

You are not signed in. Login or sign up in order to post.