I have a nested list of 0s and ones such as :
L = [[1, 0, 1],
[0, 0, 0],
[0, 0, 1]]
I want to check if any ones are diagonal to each other. The nested list can come in any size, as long as the length of the sublists is equal to the length of the whole list (it's a square). So if I ran it on the above list, it would return False, because of two ones being diagonal.
My current code is:
for num, i in enumerate(List):
for count, m in enumerate(i):
key1 = True
key2 = True
key3 = True
key4 = True
num1 = num
num2 = num
num3 = num
num4 = num
count1 = count
count2 = count
count3 = count
count4 = count
if m == 1:
while key1 or key2 or key3 or key4:
#print(key1, key2, key3, key4)
try:
if List[num1 + 1][count1 + 1] == 1:
print(List[num1 + 1][count1 + 1])
return False
num1 += 1
count1 += 1
except IndexError:
key1 = False
try:
if List[num2 - 1][count2 + 1] == 1:
if num2 > 0:
print(List[num2 - 1][count2 + 1])
return False
num2 -= 1
count2 += 1
except IndexError:
key2 = False
try:
if List[num3 + 1][count3 - 1] == 1:
if count3 > 0:
print(List[num3 + 1][count3 - 1])
print(num3 + 1, count3 - 1)
return False
num3 += 1
count3 -= 1
except IndexError:
key3 = False
try:
if List[num4 - 1][count4 - 1] == 1:
if count4 > 0 and num4 > 0:
print(List[num4 - 1][count4 - 1])
return False
num4 -= 1
count4 -=1
except IndexError:
key4 = False
return True
The code scans the list for 1s, and when one is found, it looks at its four corners and searches them. It continues to search in the direction of the corner, moving one grid at a time. If another 1 is found, it returns false. Once all possible diagonal grids are searched (up to returning index error), the code moves to the next 1 that is found. Once every single 1 is searched and none of them find any diagonal is found, the code returns true.
It feels clunky and inefficient, but I'm not sure how to compact it. Is there a shorter way to do this?