[Tutor] point and polygon
Shi Mu
samrobertsmith at gmail.com
Sun Nov 6 11:52:33 CET 2005
why the following code report error?
"""
Is given point in polygon?
"""
def pointInPoly(point, pointsList):
"Return True if point is contained in polygon (defined by
given list of points.)"
assert len(pointsList) >= 3, 'Not enough points to define a
polygon (I require 3 or more.)'
assert len(point) >= 2, 'Not enough dimensions to define a
point(I require 2 or more.)'
# If given values are ints, code will fail subtly. Force them to floats.
x,y = float(point[0]), float(point[1])
xp = [float(p[0]) for p in pointsList]
yp = [float(p[1]) for p in pointsList]
# Initialize loop
c=False
i=0
npol = len(pointsList)
j=npol-1
while i < npol:
if ((((yp[i]<=y) and (y<yp[j])) or
((yp[j]<=y) and(y<yp[i]))) and
(x < (xp[j] - xp[i]) * (y - yp[i]) / (yp[j] -
yp[i]) + xp[i])):
c = not c
j = i
i += 1
return c
if __name__ == '__main__':
print 'Simple pointInPoly() test...'
pointA = (3,30)
pointB = (8,8)
poly = (-1,-1), (6,-1), (5,6), (0,5)
assert pointInPoly(pointA, poly)
assert not pointInPoly(pointB, poly)
More information about the Tutor
mailing list