I have this code
for i, j in zip(range(r, -1, -1), # Checks high diagonal on left.
range(c, -1, -1)):
if chess_board[i][j] == 1:
return False
for i, j in zip(range(r, n, 1), # Checks lower diagonal on left.
range(c, -1, -1)):
if chess_board[i][j] == 1:
return False
My question is are there alternatives, more basic and clear ways of expressing this than using zip?
Edit:
So would it be possible to have this code without using zip?
for i, m in zip(range(r, -1, -1), range(c, -1, -1)): # Checks high diagonal on left.
if chess_board[i][m] == 1:
return False
for i, m in zip(range(r, n, 1), range(c, -1, -1)): # Checks lower diagonal on left.
if chess_board[i][m] == 1:
return False
CodePudding user response:
if you want more basic, you could do a forloop where you continually index on the range
for i in range(min(r,c)):
r1 = range(r, -1, -1)[i]
r2 = range(c, -1, -1)[i]
print(f"{r1}, {r2}")
or directly calculate your values
for i in range(min(r,c)):
r1 = r - i
r2 = c - i
print(f"{r1}, {r2}")
CodePudding user response:
You can use a list comprehension / generator expression to create the index tupples:
>>> r=5
>>> c=4
>>> for (i, j) in ((r-y-1, c-y-1) for y in range(min((r,c)))):
... print(f"{i}, {j}")
...
4, 2
3, 1
2, 0
Also have a look at the itertools module, it allows for even more advanced constructions, such as visiting all cells of an 8x8 chess board:
>>> from itertools import product
>>> for (i, j) in product(range(8),range(8)):
... print(f"{i}, {j}")
...
0, 0
0, 1
0, 2
0, 3
0, 4
0, 5
0, 6
0, 7
(...)
7, 0
7, 1
7, 2
7, 3
7, 4
7, 5
7, 6
7, 7