Home > Back-end >  Chessboard pattern using x's and blanks in Python
Chessboard pattern using x's and blanks in Python

Time:10-11

I just star want to understand how can I make a chess board pattern in Python. I want to make it with "X" and blanks in pattern as below (where 1 = X and 0 = blank) :
101010101010
010101010101
101010101010
010101010101
101010101010
010101010101
101010101010
010101010101

What I've tried is to make first similiar using 1 and 0 but I don't know how change it for X's and blanks

def chess(dimensions):
for row in range(dimensions**2):
    if row % dimensions == 0 and row != 0:
        print()
        print((row   1) % 2, end=' ')
    else:
        print((row   1) % 2, end=' ')       
print(chess(9))

Could you please check my code and advise?

CodePudding user response:

def chess(dimensions):

    for row in range(dimensions**2):
        if row % dimensions == 0 and row != 0:
            print()
        print('X' if (row   1) % 2 else ' ', end=' ')

print(chess(9))

CodePudding user response:

Here's an alternate solution using string repetition:

def chess(n, tiles="X "):
    row = tiles*n
    return "\n".join(row[::(-1)**i][:n] for i in range(n))

Output:

>>> print(chess(9))
X X X X X
 X X X X
X X X X X
 X X X X
X X X X X
 X X X X
X X X X X
 X X X X
X X X X X

>>> print(chess(9, "10"))
101010101
010101010
101010101
010101010
101010101
010101010
101010101
010101010
101010101

Another possibility is to alternate between two slices, which is more efficient than repeatedly reversing row:

def chess(n, tiles="X "):
    row = tiles*n
    rows = (row[:n], row[-n:])
    return "\n".join(rows[i % 2] for i in range(n))
  • Related