One line Python by calculating the cross product of two vectors


  • 1

    Well, I know it's a little bit "long" for one line but it's still one line.

    For given three points p1 = (x1,y1), p2 = (x2,y2), p3 = (x3,y3), we calculate the cross product of vector V1 = (p1 -> p2) and V2 = (p2 -> p3). If all cross products have same signs (all >= 0 or all <= 0), return True.

    class Solution(object):
        def isConvex(self, p):
            """
            :type p: List[List[int]]
            :rtype: bool
            """
            return all(((p[i-1][0]-p[i][0])*(p[i][1]-p[i+1][1]) - \
                   (p[i][0]-p[i+1][0])*(p[i-1][1]-p[i][1])) >= 0 \
                   for i in range(-1, len(p)-1)) or \
                   all(((p[i-1][0]-p[i][0])*(p[i][1]-p[i+1][1]) - \
                   (p[i][0]-p[i+1][0])*(p[i-1][1]-p[i][1])) <= 0 \
                   for i in range(-1, len(p)-1))
    

Log in to reply
 

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