Domanda

I am using following code for checking if point lie inside or outside of a given polygon:

def point_in_poly(x,y,poly):

  n = len(poly)
  inside = False

  p1x,p1y = poly[0]
  for i in range(n+1):
      p2x,p2y = poly[i % n]
      if y > min(p1y,p2y):
          if y <= max(p1y,p2y):
              if x <= max(p1x,p2x):
                  if p1y != p2y:
                      xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                  if p1x == p2x or x <= xints:
                      inside = not inside
      p1x,p1y = p2x,p2y

  return inside

Now xints is not defined in the function. What will happen if if p1y != p2y:condition failed then there would be no xints and when it will go to check next condition if p1x == p2x or x <= xints:it wont have `xints. It is bothering me. I guess I am missing something silly here.Any help appreciated.

È stato utile?

Soluzione

To answer your question:

What will happen if...

In the case where p1y == p2y and p1x != p2x you will get a NameError. You should initialise e.g.

xints = None

then test that it has been set to something sensible:

if p1x == p2x or (xints is not None and x <= xints):
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top