如何将嵌套的for循环复杂性降低到python中的单个循环?

编程入门 行业动态 更新时间:2024-10-24 06:31:27
本文介绍了如何将嵌套的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中的单个循环?

本文发布于:2023-11-29 23:09:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647911.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   复杂性   如何将   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!