André Caruso André Caruso - 1 month ago 4
Python Question

Keeping Python from spacing after breaking a line when printing a List

(yes, I've searched all around for a solution, and, if did I see it, I wasn't able to relate to my issue. I'm new to Python, sorry!)

I've got a work to do, and it says to me:
"User will input X and Y. Show a sequence from 1 to Y, with only X elements each line."

e.g
2 4 as entrance

1 2

3 4


e.g 2 6

1 2

3 4

5 6


Okay... So, I thought on doing this:

line, final = input().split()
line = int(line)
final = int(final)
List = []
i = 0
total = (final // line)
spot = 0
correction = 0
k = 1

if i != final:
List = list(range(1, final + 1, 1))
i += 1

while k != total:
spot = line * k + correction
correction += 1
k += 1
list.insert(List, spot, '\n')

print(*List)


Ok. So I managed to build my List from 1 to the "final" var.
Also managed to find on which spots (therefore, var "spot") my new line would be created. (Had to use a correction var and some math to reach it, but it's 10/10)

So far, so good.
The only problem is this work is supposed to be delivered on URI Online Judge, and it DEMANDS that my result shows like this:

2 10 as entrance

1 2

3 4

5 6

7 8

9 10


And, using the code I just posted, I get this as a result:

1 2

3 4

5 6

7 8

9 10


Thus, it says my code is wrong. I've tried everything to remove those spaces (I think). Using sys won't work since it only prints one argument. Tried using join (but I could have done it wrong, as I'm new anyway)

Well, I've tried pretty much anything. Hope anyone can help me.

Thanks in advance :)

Answer

The problem with the approach you're using is a result of a space being printed after each "\n" character in the series. While the idea was quite clever, unfortunately, I think this means you will have to take a different approach from inserting the newline character into the list.

Try this approach: (EDITED)

x, y = input().split()
x, y = int(x), int(y)

for i in range(1, y+1):
    if i % x == 0 or i == y:
        print(i)
    else:
        print(i, end=" ")

Output for 3 11

1 2 3
4 5 6
7 8 9
10 11

Output for 2 10

1 2
3 4
5 6
7 8
9 10
Comments