Vishal Singh
Vishal Singh

Reputation: 6234

How to remove this extra trailing space at the end of each line in python3

I am trying to print this pattern using print() function in python3.

        0
      0 1 0
    0 1 2 1 0
  0 1 2 3 2 1 0
    0 1 2 1 0
      0 1 0
        0

the following are the two ways I implemented this.

numeric approach

limit = int(input())
space = '  '
for i in range(0, limit + 1):
    print(space * (limit - i), end='')

    for j in range(2 * i + 1):
        if j > i:
            print(i - (j - i), end=' ')
        else:
            print(j, end=" ")
    print()


for i in range(0, limit)[::-1]:
    print(space * (limit - i), end='')

    for j in range(2 * i + 1)[::-1]:

        if j > i:
            print(i - (j - i), end=' ')
        else:
            print(j, end=" ")
    print()

string and list comprehension approach

gap = '  '
y = int(input())
y = y + 1
for n in range(1, y + 1):
    str1 = ' '.join(str(e) for e in list(range(n)))
    str2 = ' '.join(str(e) for e in list(range(n - 1))[::-1])
    print(gap * (y - n) + str1 + " " + str2.strip())

for n in range(1, y)[::-1]:
    str1 = ' '.join(str(e) for e in list(range(n)))
    str2 = ' '.join(str(e) for e in list(range(n - 1))[::-1])
    print(gap * (y - n) + str1 + " " + str2.strip())

the pattern is printing right but when I am submitting this to online judge it do not accept.

wrong answer 1st lines differ - expected: '    0', found: '    0 '

it expects to remove that extra space after the 0.

PROBLEM: In both of the code snippet I am unable to remove the last line extra space.
I do not know how to achieve this Pattern and also not to have that extra space after the number at the end of each line.

Upvotes: 0

Views: 194

Answers (1)

Acccumulation
Acccumulation

Reputation: 3591

The problem appears to be the expression gap * (y - n) + str1 + " " + str2.strip(). For the first line, str is null, so you have str1 followed by a space, followed by nothing, which means that you have a space at the end of your line. The solution is to add the lists together first, then join:

for n in range(1, y + 1):
    list1 = [str(e) for e in list(range(n))]
    list2 = [str(e) for e in list(range(n - 1))[::-1]]
    print(gap * (y - n)+" ".join(list1+list2))

BTW, an alternative to list(range(n - 1))[::-1] is list(range(n-2,-1,-1)).

You can also combine list comprehensions with various tricks, such as

[str(e) if e < n else str(2*n-e) for e in range(2*n+1) ]

Upvotes: 2

Related Questions