I have a 2D list below:
a = [[3, 10], [7, 11], [7, 12], [8, 11], [8, 12], [12, 8], [12, 9], [13, 8], [13, 9], [14, 6], [14, 7], [15, 8], [17, 6], [18, 6]]
There are 4 points that can form a square:
[7, 11], [7, 12], [8, 11], [8, 12]
or this:
[12, 8], [12, 9], [13, 8], [13, 9]
This is my code:
def find_square(a):
i = 0
result = []
while(i < len(a)):
if a[i][0] == a[i + 1][0]:
if a[i][1] == a[i + 2][1]:
if a[i + 2][0] == a[i + 3][0]:
if a[i + 1][1] == a[i + 3][1]:
result.append([a[i][0] + 1, a[i][1] + 1])
i += 4
else:
i += 3
else:
i += 2
else:
i += 1
return result
Output:
[8, 12], [13, 9]
This code will return the last point (bottom right) of the square. I want to check if there are exist 4 points that can form a square with the side of 1 and return the bottom right point. What is a better way to implement this code?
The 2D list is assumed to be sorted in ascending order of x-coordinate.
Update:
I found a case that my code has a problem:
[7, 11], [7, 12], [7, 13], [8, 11], [8, 12]
The point [7, 13] make my code cannot detect the square.