2

This piece of code generates the permutation, I'm interested to how the else: return at the end works.

all_str = []
def permu(iterable,r=None):
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = list(range(n))
    cycles = list(range(n, n - r, -1))
    all_str.append( tuple(pool[i] for i in indices[:r]))
    while True:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i + 1:] + indices[i:i + 1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                all_str.append( tuple(pool[i] for i in indices[:r]))
                break
        else: # here
            return
permu("abcde",4)

what is the else at the bottom referring to? I know that you can have an if in the loop and else outside the loop, but this doesn't seem to be the case as the if is already taken care of by an else.

When I remove the else: return, the function generates permutation endlessly in a repeating fashion.

I want to know this because I need to replicate this code in C++.

Any help or suggestion will be greatly appreciated :)

2
  • 1
    It's more clear to read the "for else" as "for finally". The else is executed if the for loop finishes correctly. read more. In your example, it will return (exit the while) after for finishes. Commented Nov 8, 2019 at 23:41
  • @Raphael yes! thanks! Commented Nov 8, 2019 at 23:48

3 Answers 3

2

the else clause of a for loop runs under a special circumstance: if the loop finishes without any disruption (in this case: break) the else clause will run, otherwise, it will be skipped. Namely, if the else related to the if is executed, the else of the for won't run.

Sign up to request clarification or add additional context in comments.

Comments

1

The else statement of a for loop is executed if nobody explicitely executed a break from within the for loop ( Full explanation in the python documentation https://docs.python.org/3.6/reference/compound_stmts.html#the-for-statement )

so if you want to replicate this in C++ you had to set a variable that keeps track whether you quit the for loop via a break or just because the for loop finished.

I didn't write C for ages, so there might be tiny errors in my pseudo C code.

while(bla){
  int encountered_break = 0;
  for(bla;bla;bla){
      if (bla){
      } else {
          encountered_break = 1;
          break;
      }
  }
  if(!encountered_break){
      return;
  }
}

2 Comments

fixed some errors in previous comment (now deleted as wrong and redundant): @Raphael Do you have an example of a code without break, that would not call the else section of a for loop? An example causing an exception within the for loop will just raise a normal exception so neither else: nor any code after the exception is executed. Also after reading the documentation of the for loop ( docs.python.org/3.6/reference/… ) I don't see how I could not enter the else section, except with a break.
strange: Whenever I get down votes I never get an explanation (which would help me to improve the quality of my answer) Added a link to the full documentation of the for loop in case this was the reason.
1

It's more clear to read the for else as for finally. The else is executed if the for loop finishes correctly. In your example, it will return (exit the while) after the for loop finishes.

In your example, if you remove the else: return, than the execution will always be inside the while True.

Read more about it here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.