私はUVAの問題に取り組んでいます。ポリゴンのリストを反復するために4つのネストされたループがあります(各ポリゴンには、各ポイントに座標x、すなわち、ポリゴン[0]はポリゴン[0] .xとポリゴン[0] .yである座標です。Pythonネストされたループを減らす
プログラムのforループの数を減らして、効率を上げ、実行時間を短縮しようとしています。次のように私のコードは次のとおりです。
for i in range(len(polygons)): # iterate over all the different polygons in the test case
for j in range(i+1, len(polygons)): # iterate over all the different polygons in the test case but starting from the second, in order to make comparations between polygons i and j
for a in range(len(polygons[i])):
if (isInside(polygons[i][a].x, polygons[i][a].y, polygons[j])):
union(i,j)
for a in range(len(polygons[j])):
if (isInside(polygons[j][a].x, polygons[j][a].y, polygons[i])):
union(i,j)
f = 1
for a in range(len(polygons[i])): # iterate over all the different points in the polygon i
for b in range(len(polygons[j])): # iterate over all the different points in the polygon j
if (f!=0):
if(doIntersect(polygons[i][a], polygons[i][(a+1)%len(polygons[i])],polygons[j][b], polygons[j][(b+1)%len(polygons[j])])): # check if every single pair of line segments, each one made up of two points, intersect with each other
union(i,j) # the two line segments intersect so we join them by using union
f = 0
を私は次のようにitertools.productを使用して、それをより効率的に作ってみました:
def solve():
global polygons, p
ranges = [range(len(polygons)), range(1,len(polygons))]
for i, j in product(*ranges):
for a in range(len(polygons[i])):
if (isInside(polygons[i][a].x, polygons[i][a].y, polygons[j])):
union(i,j)
for a in range(len(polygons[j])):
if (isInside(polygons[j][a].x, polygons[j][a].y, polygons[i])):
union(i,j)
f = 1
ranges2 = [range(len(polygons[i])), range(len(polygons[j]))]
for a,b in product(*ranges2):
if (f!=0):
if(doIntersect(polygons[i][a], polygons[i][(a+1)%len(polygons[i])],polygons[j][b], polygons[j][(b+1)%len(polygons[j])])): # check if every single pair of line segments, each one made up of two points, intersect with each other
union(i,j) # the two line segments intersect so we join them by using union
f = 0
とにかく私のコードは、どちらの場合も同じランタイムを持っている、そこにあります私のアルゴリズムのネストされたループの数を減らす方法?任意の助けを事前に
おかげで、感謝
外部ループ用の製品がありません。*組み合わせ*を生成しています。 –