在坐标系中给定的2个点,求其他2个点,使得这4个点可以组成一个正方形。
class Squares:
def __init__(self, counts, points_list):
self.counts = counts # 坐标点的个数
self.points_list = points_list # 坐标的列表
# 计算任意2个坐标的距离
def getresult(self):
square_cnt = 0 # 初始正方形的个数为0
if self.counts <= 3:
return 0
check_list = [] # 检查4个点是否已经组成了正方形
# 由给定的2点求正方形的其它的2个顶点的坐标
for i in range(self.counts):
x1 = self.points_list[i][0]
y1 = self.points_list[i][1]
for j in range(self.counts - 1, i, -1):
x2 = self.points_list[j][0]
y2 = self.points_list[j][1]
x3 = x2 - (y2 - y1)
y3 = y2 + (x2 - x1)
x4 = x3 - (y3 - y2)
y4 = y3 + (x3 - x2)
if [x3, y3] in self.points_list:
k = self.points_list.index([x3, y3])
if [x4, y4] in self.points_list:
t = self.points_list.index([x4, y4])
# 检测4个点是否已经组成了正方形以避免重复使用
square_index = sorted([i, j, k, t])
if square_index not in check_list:
check_list.append(square_index)
square_cnt += 1
# 输出正方形的个数
return square_cnt
# 主函数
if __name__ == "__main__":
# 数据输入
points_cnt = int(input())
pointslist = []
for x in range(points_cnt):
line = input().strip().split()
pointslist.append(list(map(int, line)))
# 实例化
s = Squares(counts=points_cnt, points_list=pointslist)
print(s.getresult())
输入测试数据
8
0 0
1 2
3 1
2 -1
1 0
1 1
2 0
2 1
测试结果
参考文献
感谢作者的辛苦付出!
添加链接描述