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 :)