如何将嵌套的for循环复杂性降低到python中的单个循环? [英] How to reduce the nested for Loop complexity to a single loop in python?

查看:51
本文介绍了如何将嵌套的for循环复杂性降低到python中的单个循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

想想像同时掷两个骰子,然后发现骰子上的总和是否为偶数,但这里有一个问题,一个骰子有 6 个面,但这里两个面可以有任意数量的大小,相等和不相等甚至相等!任何人都可以建议如何在一个循环下合并它,因为我想不出任何一个?

Think of something like tossing two dices at the same time and finding if the sum on the dices is an even number but here's the catch, a dice has 6 sides but here the two can have any number of sizes, equal and not equal even! Can anyone suggest how to merge it under one loop because I can't think of any?

推荐答案

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

You can't get rid of the nested loop (you could hide it, like by using itertool.product, but it would still be executed somewhere, and the complexity would still be O(x * y)) but you can get rid of the condition, if you only need to generate the values of j that satisfy it, by adapting the range for j.

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

This way, you'll have about twice as less loops by avoiding the useless ones.

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

这篇关于如何将嵌套的for循环复杂性降低到python中的单个循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆