【问题标题】:How to reduce the nested for Loop complexity to a single loop in python?python - 如何将嵌套的for循环复杂性降低为python中的单个循环?
【发布时间】:2020-12-09 17:13:36
【问题描述】:
for i in range(0,x):
        for j in range(0,y):
            if (i+j)%2 == 0:

想象一下同时抛两个骰子,然后找出骰子的总和是否为偶数,但问题是,骰子有 6 个面,但这里两个可以有任意数量的大小,相等或不相等平等甚至! 谁能建议如何将它合并到一个循环下,因为我想不出任何?

【问题讨论】:

  • 想做什么?没有上下文:这是一个降低复杂性的程序:pass
  • 我们不知道您要做什么 - 例如,如果条件不满足怎么办?您使用任何值吗?还是只生成满足条件的j 的值?
  • 这能回答你的问题吗? Python Reducing Nested Loops
  • 您所写的内容表明您正在使用网格,如果是这样,那么一定要保持其最易读的方式。将其变成一个循环最终将具有相同的复杂性(因为您将使用range(x*y))并且性能变化不大:)
  • 不,就像想像同时掷两个骰子并找出骰子上的总和是否为偶数,但这里有一个问题,一个骰子有 6 个面,但这里两个可以有任何大小的数量,相等和不相等!

标签: python nested-loops


【解决方案1】:

基于Python combine two for loops,您可以通过如下方式导入itertools将两个for循环合并到一行中:

import itertools

for i, j in itertools.product(range(0,x), range(0,y)):
    if (i+j)%2 == 0:

【讨论】:

  • 这不会改变算法的复杂性。
【解决方案2】:

你无法摆脱嵌套循环(你可以隐藏它,比如使用itertool.product,但它仍然会在某个地方执行,复杂度仍然是 O(x * y))但你可以摆脱条件,如果你只需要生成满足它的 j 的值,通过调整j 的范围。

这样,通过避免无用的循环,您将减少大约两倍的循环。

for i in range(0,x):
    for j in range(i%2,y, 2):
        print(i, j, i+j)

输出:

0 0 0
0 2 2
1 1 2
1 3 4
2 0 2
2 2 4

【讨论】:

    【解决方案3】:

    对我来说,将其保留为两个循环会更干净。它更具可读性并且更容易理解正在发生的事情。但是你基本上可以做x * y 然后使用 divmod 来计算 i 和 j

    x = 2
    y = 3
    for i in range(0,x):
            for j in range(0,y):
                print(i, j, i+j)
    
    print("###")
    for r in range(x*y):
        i, j = divmod(r, y)
        print(i, j, i + j)
    

    输出

    0 0 0
    0 1 1
    0 2 2
    1 0 1
    1 1 2
    1 2 3
    ###
    0 0 0
    0 1 1
    0 2 2
    1 0 1
    1 1 2
    1 2 3
    

    【讨论】:

    • arr1=[n for n in range(0,a)] arr2=[n for n in range(0,b)] lst1=list(combinations(arr1, 2)) lst2=list(combinations(arr2, 2)) lst=lst1+lst2 res = list(OrderedDict.fromkeys(lst)) 它有这样的输出- [(0, 1), (0, 2), (0, 3 ), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (0, 5), (0, 6), (0, 7), (0, 8), (1, 5), (1, 6), (1, 7), (1, 8), (2, 5), (2 , 6), (2, 7), (2, 8), (3, 5), (3, 6), (3, 7), (3, 8), (4, 5), (4, 6 ), (4, 7), (4, 8), (5, 6), (5, 7), (5, 8), (6, 7), (6, 8), (7, 8)]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多