Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce the nested for Loop complexity to a single loop in python?

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

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?

like image 803
Chandrachud Pati Avatar asked Feb 20 '26 19:02

Chandrachud Pati


2 Answers

based on Python combine two for loops, you can merge two for loops in a single line by importing itertools as below:

import itertools

for i, j in itertools.product(range(0,x), range(0,y)):
    if (i+j)%2 == 0:
like image 197
Ali Ülkü Avatar answered Feb 23 '26 08:02

Ali Ülkü


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)

Output:

0 0 0
0 2 2
1 1 2
1 3 4
2 0 2
2 2 4
like image 44
Thierry Lathuille Avatar answered Feb 23 '26 09:02

Thierry Lathuille