Simple Python


  • 0
    P

    We calculate the distances between every pair of points (6 in total). We are guarenteed to have a square if we end up with only two values: the side length, and the diagonal. Of course the 4 points have to be distinct, so we need to check for that too.

    import itertools
    class Solution(object):
        def find_dis(self,p1,p2):
            return (p1[0] - p2[0])**2 + (p1[1] - p2[1])**2
        def validSquare(self, p1, p2, p3, p4):
            s = set()
            for pair in itertools.combinations([p1,p2,p3,p4],2):
                if pair[0] == pair[1]:
                    return False
                s.add(self.find_dis(*pair))  #The star unpacks the tuple into function arguments
            return len(s) == 2
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.