I am trying to solve the n-queen validation problem where the user first prints an n by n matrix for our sake, 8 by 8 from 0 - 63. The user keys in the Position of the queens then our model evaluates whether they are attacking each other. I fail to get through the second test case when queen input = " 59 24 41 19 52 13 30 47 " where clearly 41 and 47 See Q on the same row. The program should automatically produce a "FAIL" as two queens on the same row attack each other. Below is my code and required output :
# Get the size of the board from the user.
n = int(input("n: "))
# Print the board with numbers.
s =''
for i in range(n):
for j in range(n):
z = i * n + j
if j != 0:
s += ' '
if z < 10:
s += ' '
s += str(z)
if i != j:
s += '\n'
print(s)
# Get the queens from the user.
queens = list(map(int, input("Queens: ").split()))
# Print the board with queens.
s =''
for i in range(n):
for j in range(n):
z = i * n + j
if j != 0:
s += ' '
if z < 10:
if z in queens:
z = " Q"
else:
s += ' '
elif z > 10:
if z in queens:
z = " Q"
else:
s +=""
s += str(z)
if i != j:
s += '\n'
print(s)
# Check if the queens are in the same row or diagonal.
for i in range(n):
for j in range(i+1, n):
try:
if queens[i] == queens[j]:
print("FAIL")
exit()
if abs(queens[i] - queens[j]) == abs(i-j):
print("FAIL")
exit()
except IndexError:
pass
# If the queens are not in the same row or diagonal, print success.
print("--> SUCCESS <--")
What do I need to edit to produce a correct output? Code refactoring is appreciated

abs(queens[i] - queens[j]) == abs(i-j)is not a correct check. The index in the queens list is of no importance. If you would shuffle the input list, the result should not be impacted. Yet, withabs(i-j)this comparison gives a significance to how far apart two queen positions are in the input list.To verify if two queens are in the same row, you should first extract the row from a given position. For that you can use division by 8:
If this comparison is true, then both queens are on the same row. A similar thing can be done to check if two queens share the same column:
For diagonal checks, you should compare the sum of a position's row and column (for one type of diagonal) or the difference of a position's row and column.
Thus it makes sense to first extract from all positions the rows and the columns, and then continue from there.
You could also count the distinct number of position rows and check there are distinct rows occupied. Same for columns and for diagonals. To get distinct values, you can create a
set(which can only store unique values, ignoring duplicates). If the set has fewer values than , you know there is a duplicate.You should also check that each position is an integer between 0 and ² (excluded).
Here is all that combined in a function:
You could use that as follows: