lundi 3 décembre 2018

Creating a Rhombus with numbers in python

Create a Rhombus through numbers if i input a number it should print the number of lines as same as input number and print the numbers upto given number

Examples :

If the input is 4

This will be the expected output.

       1
     1 2 3
     1 2 3
       1

If the input is 5

This will be the expected output.

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

If the input is 7

This will be the expected output.

             1
           1 2 3
         1 2 3 4 5
       1 2 3 4 5 6 7
         1 2 3 4 5
           1 2 3
             1

I have tried,

size = 4
maxlen = len(str(size * size))
m = size * 2 - 1
matrix = [[' ' * maxlen] * m for _ in range(m)]

for n in range(size * size):
     r = n // size
     c = n % size
     matrix[c + r][size - r - 1 + c] = '{0:{1}}'.format(n + 1, maxlen)

print '\n'.join(''.join(row) for row in matrix)

Aucun commentaire:

Enregistrer un commentaire