如何解决计算列表中每三个连续点的叉积,并检查所有叉积是否具有相同的符号
我使用“ Point”类和“ Polygon”类创建了一个多边形的顶点列表。现在,检查多边形的类型,是否为“凹形”。或“凸”多边形,我想计算顶点列表中存在的每三个连续点的叉积。例如,考虑一个列表:顶点= [p1,p2,p3,p4,p5,p6] 。考虑到此列表,序列应为p1,p2,p3 ... p2,p3,p4 ... p3,p4,p5 ... p4,p5,p6 ...以及p5,p6,p1。我的意思是,最后一个叉积将在列表的最后2个元素和第1个元素之间,因为多边形是一个闭合图形。 然后,在计算之后,程序应检查所有叉积是否均为-ive(负)或全部为+ ive(正),因为这是多边形凸的条件。
class Polygon:
def __init__(self,*vertices):
self.vertices=[Polygon.Point(v[0],v[1]) for v in vertices]
def CrossProduct(self,A,B,C):
return (B.x - A.x) * (C.y - B.y) -(B.y - A.y) * (C.x - B.x)
@property
def shape(self): #Method for determining the type of polygon i.e. Convex or concave
# if (all cross product >=0 or all cross products <=0):
#return 'Convex'
# return 'Concave'
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
### MAIN PROGRAM ###
poly1 = Polygon((3,4),(5,11),(12,8),(9,5),6)) #Concave Polygon
poly2 = Polygon((5.09,5.80),(1.68,4.90),(1.48,1.38),(4.76,0.10),(7.00,2.83)) #Convex Polygon
print(poly1.shape)
print(poly2.shape)
解决方法
使用zip(..)创建所有需要的三元组,并使用all(..)进行检查:
class Polygon:
def __init__(self,*vertices):
self.vertices=[Polygon.Point(v[0],v[1]) for v in vertices]
def CrossProduct(self,A,B,C):
return (B.x - A.x) * (C.y - B.y) -(B.y - A.y) * (C.x - B.x)
@property
def shape(self): #Method for determining the type of polygon i.e. Convex or concave
p0 = self.vertices[0:1]
# debugging printout of points that are going to be checked
points = list(zip(self.vertices,self.vertices[1:],self.vertices[2:] + p0))
print(*points)
print ([self.CrossProduct(*p) for p in points])
if all(self.CrossProduct(*p) >= 0 for p in points) or all(
self.CrossProduct(*p) < 0 for p in points):
return "Convex"
return "Concave"
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def __str__(self):
return f"({self.x},{self.y})"
def __repr__(self):
return str(self)
poly1 = Polygon((3,4),(5,11),(12,8),(9,5),6)) # Concave
poly2 = Polygon((5.09,5.80),(1.68,4.90),(1.48,1.38),(4.76,0.10),(7.00,2.83))
print(poly1.shape) # Concave
print(poly2.shape) # Convex
输出:
((3,8)) ((5,5)) ((12,6)) ((9,6),(3,4))
[-55,-30,-15,10]
Concave
((5.09,5.8),4.9),1.38)) ((1.68,0.1)) ((1.48,0.1),(7.0,2.83)) ((4.76,2.83),(5.09,5.8))
[11.823200000000002,11.8016,11.8216,11.8671]
Convex
,
在解决问题后,我想到了类似的东西
pp = [(3,6)]
pp = pp + pp[:(len(pp) % 3 - 1)]
print(pp)
c = list(zip(pp,pp[1:],pp[2:]))
def cross_product(p):
print(p)
pass
for pt in c:
cross_product(pt)
哪种产量:
[(3,4)]
((3,8))
((5,5))
((12,6))
((9,4))
因此,首先,您必须稍微“填充”初始列表以使其正确包裹-长度必须被3整除,以便我们可以将其打包为3点。
此后,只需在3个连续元素之间进行简单的zip压缩并进行叉积计算即可。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。