Python Print an alternation

562 Views Asked by At

I need to print a simple chessboard in Python, and it has to have 8 rows and 8 columns.

This is what I have so far:

for each_row in range(0,8):
    for each_column in range(0,8):
        print(" ", end="")
    for k in range(0, 8):
        print("x", end="o")
    print("")

It prints something like this:

xoxoxo
xoxoxo
xoxoxo
xoxoxo

but I want something like this:

xoxoxo
oxoxox
xoxoxo
oxoxox
4

There are 4 best solutions below

0
galihif On

You should use conditional if-else to print different pattern each rows

Input

for each_row in range(0,8):
    #use if else to print different pattern each row
    for each_column in range(0, 8):
        if each_row%2 ==0:
            print("x", end="o")
        else:
            print("o", end="x")
    print("")

Output

xoxoxoxoxoxoxoxo
oxoxoxoxoxoxoxox
xoxoxoxoxoxoxoxo
oxoxoxoxoxoxoxox
xoxoxoxoxoxoxoxo
oxoxoxoxoxoxoxox
xoxoxoxoxoxoxoxo
oxoxoxoxoxoxoxox
0
cristelaru vitian On

Try this:

for each_row in range(0,8):
   for each_column in range(0,8):
      print(" ", end="")
   if each_row % 2 == 0:
      for k in range(0, 8):
         print("x", end="o")
   else:
      for k in range(0, 8):
         print("o", end="x")
   print("")

or, more elegant:

for each_row in range(0,8):
   for each_column in range(0,8):
      print(" ", end="")
   for k in range(0, 8):
      print("x" if each_row % 2 == 0 else "o", end="o" if each_row % 2 == 0 else "x")    
   print("")

or:

for each_row in range(0,8):
    print(" "*8, end="")
    print(("xo" if each_row % 2 == 0 else "ox")*8)  
0
Dimitri On

Here is a clean solution to your problem:

figure = 'x'
for each_row in range(0,4):
    figure = 'x' if figure == 'o' else 'o'
    for each_column in range(0,6):
        print(figure,end="")
        figure = 'x' if figure == 'o' else 'o'
    print("")

Using a variable to keep track of the figure you want to print next time and changing it to the other as needed.

output:

xoxoxo
oxoxox
xoxoxo
oxoxox
0
Thierry Lathuille On

A general solution generating grids of any size, using some itertools.

letters = cycle('xo') creates an iterator that will yield 'x', 'o', 'x', 'o' ... in cycle indefinitely.

islice(letters, n) will give us the next n letters from it.

We need to skip one letter to shift the next line in case the size of the grid is even: we can do it with next(letters) which will get the next one (and just throw it away).

So, the code could be:

from itertools import cycle, islice

def grid(size):
    letters = cycle('xo')
    lines = []
    for _ in range(size):
        lines.append(''.join(islice(letters, size)))
        if size % 2 == 0:
            next(letters)
    return '\n'.join(lines)

Example with an odd size:

print(grid(3))
​
​
xox
oxo
xox

and with an even size:

print(grid(4))
​
​
xoxo
oxox
xoxo
oxox