algorithms

Algorithm implementations
git clone git://git.laack.co/algorithms.git
Log | Files | Refs | README

valid-square.py (1019B)


      1 def dist(p1,p2):
      2     return sqrt(((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))
      3 
      4 class Solution:
      5     def validSquare(self, p1: List[int], p2: List[int], p3: List[int], p4: List[int]) -> bool:
      6         dists = [dist(p1, p2), dist(p2, p3), dist(p3, p4), dist(p4, p1), dist(p1, p3), dist(p2, p4)]
      7         
      8         d1 = None
      9         d1_count = 0
     10         d2 = None
     11         d2_count = 0
     12 
     13         for distance in dists:
     14             if distance == 0:
     15                 return False
     16             
     17             if d1 is None:
     18                 d1 = distance
     19                 d1_count += 1
     20                 continue
     21             
     22             if distance != d1 and d2 is None:
     23                 d2 = distance
     24                 d2_count += 1
     25                 continue
     26             
     27             if distance == d1:
     28                 d1_count += 1
     29             if distance == d2:
     30                 d2_count += 1
     31             
     32 
     33         if (d1_count == 4 and d2_count == 2) or (d2_count == 4 and d1_count == 2):
     34             return True
     35         return False