Checking if a point is inside a polygon

后端 未结 3 2030
情话喂你
情话喂你 2020-11-30 21:34

I have a class describing a Point (has 2 coordinates x and y) and a class describing a Polygon which has a list of Points which correspond to corners (self.corners) I need t

3条回答
  •  旧时难觅i
    2020-11-30 22:16

    I'd like to suggest some other changes there:

    def contains(self, point):
        if not self.corners:
            return False
    
        def lines():
            p0 = self.corners[-1]
            for p1 in self.corners:
                yield p0, p1
                p0 = p1
    
        for p1, p2 in lines():
            ... # perform actual checks here
    

    Notes:

    • A polygon with 5 corners also has 5 bounding lines, not 6, your loop is one off.
    • Using a separate generator expression makes clear that you are checking each line in turn.
    • Checking for an empty number of lines was added. However, how to treat zero-length lines and polygons with a single corner is still open.
    • I'd also consider making the lines() function a normal member instead of a nested utility.
    • Instead of the many nested if structures, you could also check for the inverse and then continue or use and.

提交回复
热议问题