Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Several nested 'for' loops, continue to next iteration of outer loop if condition inside inner loop is true

I know it is terribly inefficient and ugly code, but if I have three for loops, nested inside each other such as so:

for x in range(0, 10):
    for y in range(x+1, 11):
       for z in range(y+1, 11):
           if ...

I want to break the two inner loops and continue to the next iteration of the outer loop if the if statement is true. Can this be done?

like image 310
KOB Avatar asked Jan 11 '16 15:01

KOB


People also ask

How does continue work for nested loops?

When continue statement is used in a nested loop, it only skips the current execution of the inner loop. Java continue statement can be used with label to skip the current iteration of the outer loop too.

When a loop is nested inside another loop?

A nested loop is a loop within a loop, an inner loop within the body of an outer one. How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes.

Can we put a third loop inside the inner loop of a nested loop construct?

Answer. Answer: Since the code block of a loop can include any legal C++ statements, you can place a loop inside of a loop.

Does continue break out of nested for loop?

In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues.


2 Answers

Check some variable after each loops ends:

for x in range(0, 10):
    for y in range(x+1, 11):
        for z in range(y+1, 11):
            if condition:
                variable = True
                break
            #...
        if variable:
            break;
        #...
like image 176
tglaria Avatar answered Oct 04 '22 08:10

tglaria


Another option is to use exceptions instead of state variables:

class BreakException(Exception):
    pass

for x in range(0, 10):
    try:
        for y in range(x+1, 11):
           for z in range(y+1, 11):
               if True:
                   raise BreakException
    except BreakException:
        pass

I imagine this could be especially useful if bailing out of more than two inner loops.

like image 27
MB-F Avatar answered Oct 04 '22 08:10

MB-F