How to avoid "flags"?

asked 2018-11-26 10:58:46 +0200

logomath gravatar image

I read that utilizing flags is deprecated in modern programming. Can someone explain me how to avoid it when I want to go out of multiple "for" loops?

edit retag flag offensive close merge delete

Comments

If I use a single "break" instruction, I come out of a single loop, and, for example, I need to go out of all of them.

logomath gravatar imagelogomath ( 2018-11-26 10:59:50 +0200 )edit
1

What do you mean by "flags" or "modern programming"? It depends on the exact logic, but in Python usually some boolean flag is the best way to break out of nested loops. Raising some exception can be another way.

Iguananaut gravatar imageIguananaut ( 2018-11-26 12:12:32 +0200 )edit

I mean, if we consider this example, when the flag goes to zero, I would go directly to next n, without the program having to try all other p,q,r, something like the od "goto":

N=100; v=[]   #  v = [n that cannot be written as p*q+q*r+r*p with p,q,r prime]
for n in prime_range(1,N):
    flag=True
    for p in prime_range(2,N):
        for q in prime_range(p,N):
            for r in prime_range(q,N):
                if flag and n==p*q+q*r+r*p:
                    flag=False; print n,p,q,r;  break
   if flag: v.append(n)
print v

How would you write such a program (possibly also with rising exception, which I don't know)?

logomath gravatar imagelogomath ( 2018-11-26 18:28:53 +0200 )edit

The "best" solution to dealing with deeply nested loops like this is often going to depend on the particular problem at hand. In this case you might write this as a specialized iterator and then loop over the combinations with a single for loop. Fortunately, this particular iterator has alread been written and you can do this like:

from itertools import combinations
for p, q, r in combinations(prime_range(2, N), 3):
    if n != p*q + q*r + r*p:
        v.append(n)

This way avoids lot of duplicate work as well, since it avoids recalculating prime_range([x > 2], N) so many times.

See https://docs.python.org/2/library/ite...

Iguananaut gravatar imageIguananaut ( 2018-11-28 09:31:10 +0200 )edit