Lintcode 886. Convex Polygon (Medium) (Python)

Convex Polygon

Description:

Given a list of points that form a polygon when joined sequentially, find if this polygon is convex (Convex polygon definition).

Example
Given points = [[0, 0], [0, 1], [1, 1], [1, 0]],
return True.
Explanation:
https://lintcode-media.s3.amazonaws.com/problem/E3N5G.png

Given points = [[0, 0], [0, 10], [10, 10], [10, 0], [5, 5]],
return False.

Explanation
https://lintcode-media.s3.amazonaws.com/problem/E3f02.png

Notice
There are at least 3 and at most 10,000 points.
Coordinates are in the range -10,000 to 10,000.
You may assume the polygon formed by given points is always a simple polygon (Simple polygon definition). In other words, we ensure that exactly two edges intersect at each vertex, and that edges otherwise don’t intersect each other.

Code:

class Solution:
    """
    @param point: a list of two-tuples
    @return: a boolean, denote whether the polygon is convex
    """
    def isConvex(self, point):
        # write your code here
        def crossProduct(a, b, c):
            x0, y0 = a
            x1, y1 = b
            x2, y2 = c
            return (x2-x0) * (y1-y0) - (x1-x0) * (y2-y0)

        lenP = len(point)
        pre = crossProduct(point[-1], point[0], point[1])
        for i in range(lenP):
            res = crossProduct(point[i%lenP], point[(i+1)%lenP], point[(i+2)%lenP])
            if res*pre < 0:
                print('res', res)
                print('pre', pre)

                return False
            if res != 0:
                pre = res
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值