Python减少嵌套循环

时间:2017-05-11 16:54:35

标签: python python-3.x nested-loops

所以我正在处理一个UVA问题,我有4个嵌套循环迭代多边形列表(每个多边形包含一个点列表,其中每个点包含一个整数x和y来表示它的坐标,即polygon [0]是坐标为polygon [0] .x和polygon [0] .y)的点。

我正在尝试减少程序中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

无论如何我的代码在两种情况下都有相同的运行时,有没有办法减少算法的嵌套循环数?

提前感谢任何给定的帮助,非常感谢

1 个答案:

答案 0 :(得分:2)

你的两个外部循环正在创建列表的组合;使用itertools.combinations() iterator表示。你最里面的双循环产生 carthesian产品,所以使用itertools.product() iterator

不要使用range(), just loop directly over the polygon lists; use enumerate()`生成索引来添加索引而不是使索引以相反的方式工作。

要配置部分,itertools食谱部分中的pairwise() recipe;这将让你获得所有细分。要再次循环到开头(将最后一个坐标与第一个坐标配对),只需将第一个元素的列表追加到末尾。

一旦摆脱了嵌套循环,就可以使用break来结束它们,而不是使用标志变量。

from itertools import combinations, product

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

for (i, a_poly), (j, b_poly) in combinations(enumerate(polygons), 2):
    for a in a_poly:
        if isInside(a.x, a.y, b_poly):
            union(i, j)
    for b in b_poly:
        if isInside(b.x, b.y, a_poly):
            union(j, i)

    # attach the first element at the end so you go 'round'
    a_segments = pairwise(a_poly + a_poly[:1])
    b_segments = pairwise(b_poly + b_poly[:1])
    for a_seg, b_seg in product(a_segments, b_segments):
        if doIntersect(*a_seg, *b_seg):
            union(i,j)
            break

事实上,一旦你确定某个联盟是一个联盟,你就不必继续其余的考试了。您可以使用any() function提前停止测试isInside()doIntersect函数:

for (i, a_poly), (j, b_poly) in combinations(enumerate(polygons), 2):
    if any(isInside(a.x, a.y, b_poly) for a in a_poly):
        union(i, j)
        break  # union found, no need to look further

    for any(isInside(b.x, b.y, a_poly) for b in b_poly):
        union(i, j)
        break  # union found, no need to look further

    # attach the first element at the end so you go 'round'
    a_segments = pairwise(a_poly + a_poly[:1])
    b_segments = pairwise(b_poly + b_poly[:1])
    if any(doIntersect(*a_seg, *b_seg) 
           for a_seg, b_seg in product(a_segments, b_segments)):
        union(i,j)

这不仅现在更具可读性,它还应该更有效率!