Python Patterns

Viewed 71

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)

3 Answers

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

This:

for i in range(1,rows):
    for j in range(1,i+1):  # prints at least one spacce
        print(" ", end='')

given any positive row number (f.e. rows=6) always starts with printing at least one space.

You also mangled the lower number printing loop and printed j while counting i.

Fix:

rows = int(input())

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

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

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

    for i in range(i, rows+1):   # some fixing here,
        print(i,end='')          # you mangled i/j
    print()

For this kind of formatting the string format mini language can be used:

rows = int(input())   # 5
tobeprinted=''.join(map(str,range(1,rows+1)))

for n in range(rows):
    print(f"{tobeprinted[n:]:>{rows}}")   # right align formatting
for n in range(rows-2 ,-1,-1):
    print(f"{tobeprinted[n:]:>{rows}}")   # right align formatting

Output:

12345
 2345
  345
   45
    5
   45
  345
 2345
12345

Made some changes to code (range start from 2). It works now. However, I believe your code is not the optimal way to approach this.


    rows = int(input())

    for i in range(1,rows):
        for j in range(2,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(2,i+1):
            print(" ", end='')
    for j in range(i, rows+1):
        print(j,end='')
        j = j+1   
    print()
Related