2013-03-06 105 views
0

結合兩個循環,其中P2是完全內部的P1在假設有兩個多邊形P1和P2蟒蛇

p1 = [(0, 10), (10, 10), (10, 0), (0, 0)] 
p2 = [(2, 6), (6, 6), (6, 2), (2, 2)] 

degree_of_contact = 0 

xyarrays = [p1,p2] 
p1_degree_of_contact = 0 
for x,y in xyarrays[0]: 
     if point_inside_polygon(x,y,xyarrays[1]): 
      p1_degree_of_contact += 1 

p2_degree_of_contact = 0 
for x,y in xyarrays[1]: 
     if point_inside_polygon(x,y,xyarrays[0]): 
      p2_degree_of_contact += 1 

degree_of_contact = p1_degree_of_contact + p2_degree_of_contact 

其中point_inside_polygon是決定是否有一個點在內部(真,假以其他方式)的多邊形, 其中poly是包含多邊形頂點座標的對(x,y)列表。該算法被稱爲「光線投射法

我希望以一種優雅的方式(線路編碼保存)這兩個循環結合在一個

+0

由於我認爲你的工作是相關的,看看numpy已經建立了對向量和矩陣的支持。你可以在那裏做很好的技巧(比如向量化的循環),它們純粹用C語言編寫,而且速度非常快。爲了提高速度:有很多內置的數學方法可以讓你的生活更輕鬆問題。 http://www.scipy.org/Tentative_NumPy_Tutorial – entropiece 2013-03-06 18:13:15

回答

3

下面應該工作:

degree_of_contact = 0 
for tmp1, tmp2 in [(p1, p2), (p2, p1)]: 
    for x,y in tmp1: 
     if point_inside_polygon(x, y, tmp2): 
      degree_of_contact += 1 
1
degree_of_contact = sum(point_inside_polygon(x, y, i) for i, j in ((p1, p2), (p2, p1)) for x, y in j)