I am trying to implement a code that prints an 8 by 8 matrix (0 to 63). It should however remove the initial tab spaces and the last empty line. My code is below :
JavaScript
x
12
12
1
s =''
2
for i in range(n):
3
for j in range(n):
4
z = i * n + j
5
s += ' '
6
if z < 10:
7
s += ' '
8
s += str(z)
9
s += 'n'
10
print(s)
11
12
The image Below is also the desired output
I have tried the dedent function but it fails to remove the last line as well
Advertisement
Answer
Basically all you are looking for is whenever you go to a new line, the initial space is not printed, since every newline is a j, you will need to add:
JavaScript
1
3
1
if j != 0:
2
s += ' '
3
It should work. Will look like this now:
JavaScript
1
17
17
1
s =''
2
for i in range(n):
3
for j in range(n):
4
z = i * n + j
5
6
if j != 0:
7
s += ' '
8
9
if z < 10:
10
s += ' '
11
s += str(z)
12
13
if i != j:
14
s += 'n'
15
print(s)
16
17
Let me know if it has any problems.