So I have a 2d list, named tour:
tour = [ [3, 2, 1,],
[4, 7, 9,],
[5, 6, 8,], ]
I want my code to check through this list and see if a king (chess) can go through it normally.
The code I made can be applicable on a N×N 2d list. What it does is that it starts on number 1, and checks all 9 spaces around it if there is a number 2, repeating the process till N×N. The problem is that when the number is at a side of the list the code gives an IndexError, to overcome this I made a try: except: IndexError but now when it gets to i = 6 it keeps on going infinitely
def in_list(number, listname):
"""
this function detects where a certain number is in a 2d list and returns the index of
it
"""
for i, sublist in enumerate(listname):
if (number in sublist):
return [i, sublist.index(number)]
return -1
def is_king_tour_3by3(tour):
"""
this function checks for all 9 areas around this number and if it's an IndexError
i.e. it's at the end of the list it ignores that case
"""
start = in_list(1, tour)
i = 2
counter = len(tour) * len(tour)
while True:
counter -= 1
print(i)
print(start)
try:
if(tour[start[0]][start[1] - 1] == i): #starting from checking the number on the left and going counter-clockwise
i += 1
start[1] -= 1
elif(tour[start[0] + 1][start[1] - 1] == i):
i += 1
start[0] += 1
start[1] -= 1
elif(tour[start[0] + 1][start[1]] == i):
i += 1
start[0] += 1
elif(tour[start[0] + 1][start[1] + 1] == i):
i += 1
start[0] += 1
start[1] += 1
elif(tour[start[0]][start[1] + 1] == i):
i += 1
start[1] += 1
elif(tour[start[0] - 1][start[1] + 1] == i):
i += 1
start[0] -= 1
start[1] += 1
elif(tour[start[0] - 1][start[1]] == i):
i += 1
start[0] -= 1
elif(tour[start[0] - 1][start[1] - 1] == i):
i += 1
start[0] -= 1
start[1] -= 1
except IndexError:
pass
if(i == (len(tour) * len(tour))):
return True
break
elif(counter == 0):
return False
break