Number of unique distances should be 2. (4 for sides, and 2 for diagonals)
class Solution(object): def validSquare(self, p1, p2, p3, p4): points = [p1, p2, p3, p4] dists = collections.Counter() for i in range(len(points)): for j in range(i+1, len(points)): dists[self.getDistance(points[i], points[j])] += 1 return len(dists.values())==2 and 4 in dists.values() and 2 in dists.values() def getDistance(self, p1, p2): return (p1 - p2)**2 + (p1 - p2)**2
not simple enough
class Solution(object): def validSquare(self, p1, p2, p3, p4): def D((P, Q)): return (P - Q) ** 2 + (P - Q) ** 2 S = set(map(D, itertools.combinations((p1, p2, p3, p4), 2))) return len(S) == 2 and 0 not in S
Don't need len(dists.values())==2
@aditya74: thanks for the solution! It is a nice one. It could be improved to cover a corner case where two points are the same while the other two points are also the same but different from the first two points, e.g.,
[0,0] [0,1] [0,1] [0,0]
Hopefully the author could add such kind of cases.
This case should result in False, as two sides are zero length.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.