想想像同时掷两个骰子,然后发现骰子上的总和是否为偶数,但这里有一个问题,一个骰子有 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中的单个循环?
发布评论