Learning how to use function generators in Python I practiced with the following code that finds the next permutation of a word and then uses this new word as input for the next one until there are no further permutations. So for example 'dbac' is followed by 'dacb' followed by 'dabc' and so on.
Basically two questions: 1) the use of two times break
to stop the two for-loops is there a better way to break out of the loops, and 2) the final part try: return finally: StopIteration
is this a proper construction?
def nextperm(word):
stoploop = True
while stoploop:
wordlist = [*word]
length = len(wordlist)-1
stoploop = False
for index_1 in range(length-1, -1, -1):
for index_2 in range(length, index_1-1, -1):
if wordlist[index_2] < wordlist[index_1]:
wordlist[index_2], wordlist[index_1] = wordlist[index_1], wordlist[index_2]
_first = wordlist[0:index_1+1]
_second = wordlist[-1:index_1:-1]
wordlist = _first + _second
word = ''.join(wordlist)
stoploop = True
yield word
break
if stoploop:
break
try:
return print('no further permutation possible')
finally:
raise StopIteration
so if you do:
for i, word in enumerate(nextperm('dcba')):
print(f'{i:2}, {word}')
output is:
0, dcab
1, dbca
2, dbac
3, dacb
4, dabc
5, cdba
6, cdab
7, cbda
8, cbad
9, cadb
10, cabd
11, bdca
12, bdac
13, bcda
14, bcad
15, badc
16, bacd
17, adcb
18, adbc
19, acdb
20, acbd
21, abdc
22, abcd
no further permutation possible
itertools.permutations
\$\endgroup\$