user12245018
user12245018

Reputation:

How would I print two diagonals of a square?

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

Answers (4)

Marsilinou Zaky
Marsilinou Zaky

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

Kirill Korolev
Kirill Korolev

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

Amrsaeed
Amrsaeed

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

nonamer92
nonamer92

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

Related Questions