How to make the columns of the Floyd Triangle perfectly symmetrical?

Asked

Viewed 452 times

-1

I’m developing an algorithm to form and display a Triângulo de Floyd with n lines.

The code is just below:

n = int(input(f'Digite o número de linhas: '))

m = 1
for c in range(1, n + 1):
    for i in range(1, c + 1):
        print(m, end=' ')
        m += 1
    print()

It occurs that when n <= 3 the columns are displayed perfectly symmetrical, just like the result...

1 
2 3 
4 5 6

However, if n > 3 the columns begin to present themselves desalinhadas. Example, n = 5...

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15

How could you organize the columns of the Floyd Triangle so that they are symmetrical (properly ordered) for all n <= 40?

1 answer

2


Since you only want up to n equal to 40, the highest possible value is 820, so one option is to align the numbers on the left, occupying 4 positions.

For this, just use the formatting options available:

m = 1
for c in range(1, n + 1):
    for i in range(1, c + 1):
        print(f'{m:<4}', end='')
        m += 1
    print()

In the case, <4 says to align the value to the left using 4 boxes, filling unused positions with blanks.

Browser other questions tagged

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