1

How does this recursive method work to generate permutations given a string? Could someone explain me please?

def exchange(self, s):
    if 0 == len(s):
        yield s
    else:
        for i in range(len(s)):
            for p in self.exchange(s[:i] + s[i + 1:]):
                yield [s[i]] + p
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
chelo
  • 35
  • 7

1 Answers1

1

The code has the following idea: Deliver all permutations by choosing one element from the input and then deliver all permutations of the remaining elements, prepended by the chosen element. After this, repeat with another element.

So, if you have as input [0, 1, 2], then the code uses the first element (0) and builds all permutations of the remaining elements (1 and 2). (These permutations are [1, 2] and [2, 1] of course.)

Then it delivers (yields) the 0 prepended to [1, 2] and then the 0 prepended to [2, 1], i. e. [0, 1, 2] and [0, 2, 1].

Then it continues and chooses the next element (1). It then builds the permutations of the remaining elements (0, 2) (i. e. [0, 2] and [2, 0]).

And so forth.

Alfe
  • 56,346
  • 20
  • 107
  • 159