I need to make a chessboard pattern filled with 0 and 1 but it it doesn't have to be square table I need to get rows and columns from user
just an example:
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
0 1 0 1 0 1 0 1
1 0 1 0 1 0 1 0
I have the solution but I couldn't understand the last row of code (table[i][j] = int(not table[i][j-1])
)
can we solve it using another method?
m = int(input("insert number of rows: "))
n = int(input("insert number of colomns: "))
table = list()
for i in range(0,m):
if i%2 == 0 :
table[i][0] = 1
else:
table[i][0] = 0
for j in range(1,n):
table[i][j] = int(not table[i][j-1])
print("print the table with chessboard pattern")
for i in range(0,m):
for j in range(0,n):
print(table[i][j],end='')
print()
CodePudding user response:
You'll have a simpler time with a nested list comprehension that uses the x
and y
coordinates of the cell being generated and the modulo operator %
to alternate between two values:
n_rows = n_cols = 5
table = [
[((x y 1) % 2) for x in range(n_cols)]
for y in range(n_rows)
]
for row in table:
print(*row)
prints out
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
The list comprehension can be written out as nested for loops, too.
table = []
for y in range(n_rows):
row = []
for x in range(n_cols):
row.append((x y 1) % 2)
table.append(row)
CodePudding user response:
You will have an error on line 6 because you can't assign a value to an index that doesn't exist..
You can do this instead:
m = int(input("insert number of rows: "))
n = int(input("insert number of colomns: "))
table = []
for i in range(m):
if i%2==0:
table.append([0 j%2 for j in range(n)])
else:
table.append([0 j%2 for j in range(1, n 1)])
You could also print it like this:
print("".join([str(row).replace('[', '').replace(']', '\n').replace(', ', ' ') for row in table]))