Search code examples
pythonloops

Python Patterns


I am not getting how to do it, I keep on running into a problem.

The following is the code:

rows = int(input())

for i in range(1,rows):
    for j in range(1,i+1):
        print(" ", end='')

    for j in range(i, rows+1):
        print(j, end='')
    print()

for i in range(rows,0,-1):
    for j in range(1,i+1):
        print(" ", end='')

    for i in range(i, rows+1):
        print(j,end='')
        j = j+1   
    print()
**My Output**
 12345
  2345
   345
    45
     5
    45
   345
  2345
 12345
**Expected Output**
12345
 2345
  345
   45
    5
   45
  345
 2345
12345

The space in the first column.

How to remove it ????

here, rows = 6 (as input from the user)


Solution

  • I think this is somewhat cleaner:

    lst = [str(i) for i in range(1, rows+1)]
    for i in range(rows):
        print((" "*i) + "".join(lst[i:]) )
    
    for i in range(rows-2, -1, -1):
        print((" "*i) + "".join(lst[i:]) )
    

    which results in:

    12345
     2345
      345
       45
        5
       45
      345
     2345
    12345