Matrix in Python 3

Asked

Viewed 33 times

-1

I wanted my program to run the following.

        1 
      2 1
    3 2 1
5 4 3 2 1

And the same for any other number. My code is like this:

def matriz2(num_linhas):
    for linha in range(1,num_linhas+1):
        for i in range(linha,0,-1):
            print(i,end=' ')
        print()

It’s almost all but the spaces are missing before the numbers and I’m not able to do it.

1 answer

2

Micro,

A possible solution would be for you to print the blanks before your second for, something like that:

print((num_linhas -  linha) * "  ", end="")

With this you would generate the spaces to the left before printing, see that here was also used the end empty to avoid line breaking. With this, your code would look like this:

def matriz2(num_linhas):
  for linha in range(1,num_linhas+1):
    print((num_linhas -  linha) * "  ", end="")
    for i in range(linha,0,-1):
      print(i,end=' ')
    print()

See online: https://repl.it/repls/NarrowUnderstatedAccess


You can also create a variable and add the numbers and spaces, printing only once in the for main, in this example I used f-string and also of rjust to generate the spaces:

def matriz2(num_linhas):
  for linha in range(1,num_linhas+1):
    toPrint = ""
    for i in range(linha,0,-1):
      toPrint = f"{toPrint}{i} "
    print(toPrint.rjust(num_linhas * 2))

See online: https://repl.it/repls/PettyGigaDifferences


Here another way of how this can be done, just as an example, can be sure that there are other ways of doing:

def matriz(num_linhas):
  for linha in range(1, num_linhas+1):
    print("".join([str(num) + " " for num in range(num_linhas - (num_linhas - linha), 0, -1)]).rjust(num_linhas * 2))

Here I use the join to turn a list into a string and rjust to put the blanks, I also use the str to turn the number into a string.

See this other online example: https://repl.it/repls/OffshoreOutstandingFilesize

Browser other questions tagged

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