Pyramid of numbers in python

2

I must make a pyramid that something like this  n = 5

1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

but what I try to do gives me that way

number n: 6

0 1 2 3 4 5 0
1 2 3 4 5 1
2 3 4 5 2
3 4 5 3
4 5 4
5 5
6

this is the code

numero=input("numero n: ")

numcol=0

while numcol<=numero:
   fila=numcol

    while (fila<numero):
       print fila,
       fila=fila+1

    print numcol,
    numcol=numcol+1
    print "\t"

XD help

    
asked by Wolf 16.10.2018 в 05:15
source

2 answers

1

Using comprehension of lists you can solve it in a very compact way:

lineas = 5
print("\n".join([str(l)*l for l in range(0,lineas+1)]))
  • We rely on the method * of the chains that replicate the same%% of% times a given string
  • Then with n we generate a list for each line with the number and length desired in each case
  • With [str(l)*l for l in range(0,lineas+1)] we join each line in a single chain with a line break for each element
answered by 16.10.2018 в 15:29
0

Well, let's start.

What I would do would be to make a string with the number and a space, and then print the string

numero=int(input("numero n: "))

numcol=0

while numcol<numero:
    fila=numcol+1
    cont=0
    m=""
    while(cont<fila):
        m=m+str(numcol+1)+" " # si no necesitas el espacio, seria m=m+str(numcol+1)
        cont+=1
    print m
    numcol=numcol+1

Basically, row would keep the number that goes in each row, for example, if it is row 1, then save the 1, and so on. With cont, what I do is repeat that number the same number of times that number dictates, if row is equal to 1, then, m will be equal to "1", if row is equal to 2, m will be equal to "2" 2 "and then, with the print m, I'm showing the rows below the other one, if you enter n = 5 in this way:

1
2 2
3 3 3 
4 4 4 4 
5 5 5 5 5 

See that I did not put, numcol less than or equal to number, but less strict, since if equal, would repeat n + 1 times and the last row of the previous example would be "6 6 6 6 6 6 "

Greetings and I hope you serve!

    
answered by 16.10.2018 в 05:43