给定2D空间中四个点的坐标 p1, p2, p3 和 p4,如果这四个点构成一个正方形,则返回 true 。
点的坐标 pi 表示为 [xi, yi] 。输入 不是 按任何顺序给出的。
一个 有效的正方形 有四条等边和四个等角(90度角)。
解:
题目比较简单,按照定义去判断。
我这里的思路是找到点p1的对角点,然后判断四条边相等(两组对面分别相等的四边形是平行四边形),并且有直角三角形(有直角的,并且四条边相等的平行四边形是正方形)。
最开始的版本,非常长,并且很丑:
from typing import List
class Solution:
@staticmethod
def distance2(p1, p2):
return (p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2
def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
p_list = [p1,p2,p3,p4]
sorted_p_list = sorted(p_list)
if sorted_p_list[0] == sorted_p_list[1] or sorted_p_list[2] == sorted_p_list[3]:
return False
distance2s = [ self.distance2(p1, point) for point in p_list ]
# 找四条等边
fourEqualEdge = False
fourEqualAngle = False
for point in p_list:
if point == p1 :
continue
if self.distance2(p1, point) == max(distance2s):
# point 是对点
other_points = [p for p in p_list if p != point and p != p1]
distance2s_p2 = [self.distance2(p, point) for p in other_points]
distance2s_p1 = [self.distance2(p, p1) for p in other_points]
edges = distance2s_p1
edges.extend(distance2s_p2)
#print(f"edges={edges}")
if all( x == edges[0] for x in edges):
fourEqualEdge = True
if 2*edges[0] == max(distance2s):
fourEqualAngle = True
return fourEqualEdge and fourEqualAngle
进行了一些修改:
规范了函数名称和变量名称;
去掉了无用的变量:p_list,fourEqualEdge,fourEqualAngle;
使用any()和all() 代替循环。
代码看起来简洁了很多:
from typing import List
class Solution:
@staticmethod
def distance(point1, point2):
"""point1和point2距离的平方"""
return (point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2
def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
sorted_p_list = sorted([p1, p2, p3, p4])
# 如果有重复的点,则返回False
if any(sorted_p_list[i]==sorted_p_list[i+1] for i in range(3)) :
return False
max_distance = max([self.distance(p1, point) for point in sorted_p_list])
for point in sorted_p_list:
if self.distance(p1, point) == max_distance:
# point 是对角点
other_points = [p for p in sorted_p_list if p != point and p != p1]
distance2s_p2 = [self.distance(p, point) for p in other_points]
distance2s_p1 = [self.distance(p, p1) for p in other_points]
distance2s_p1.extend(distance2s_p2)
edges = distance2s_p1
if all(x == edges[0] for x in edges) and 2 * edges[0] == max_distance:
return True
return False