Reputation:
So for a example, if a user had input 2, the output will be xo ox
and if the user inputs 3 it will output xox oxo xox
etc. The code I have so far only outputs the diagonal of a square in the opposite direction.
size = int(input("Size of the square: "))
for i in range(size):
line = ""
for j in range(size):
if i+j == size-1:
line += "x"
else:
line += "o"
print(line)
In this example, when you input 3 for example, you will get as an output:
oox
oxo
xoo
Upvotes: 0
Views: 1173
Reputation: 1047
You can solve it using one loop as follows:
size = 3
result = []
for x in range(size)[::-1]:
line = list("o" * size)
line[x] = "x"
result.append("".join(line))
print(*result)
Upvotes: 0
Reputation: 1006
In case you're in love with generators
square = "\n".join(["".join(["x" if i == j or i == size - j - 1 else "o" for j in range(size)]) for i in range(size)])
Upvotes: 0
Reputation: 316
You can use numpy fill_diagonal for a more efficient approach
size = 3
a = np.chararray((size, size))
a[:] = 'o'
np.fill_diagonal(a, 'x')
np.fill_diagonal(np.fliplr(a), 'x')
output
a = chararray([[b'x', b'o', b'x'],
[b'o', b'x', b'o'],
[b'x', b'o', b'x']], dtype='|S1')
Upvotes: 0
Reputation: 1917
size = int(input("Size of the square: "))
for i in range(size):
line = ""
for j in range(size):
if i == j: # main diagonal
line += "x"
elif i + j == size - 1: # secondary diagonal
line += "x"
else:
line += "o"
print(line)
Upvotes: 1