I don't understand this recursive method in python to generate permutations -
how recursive method work generate permutations given string? explain me please?
def exchange(self, s): if 0 == len(s): yield s else: in range(len(s)): p in self.exchange(s[:i] + s[i + 1:]): yield [s[i]] + p
the code has following idea: deliver permutations choosing 1 element input , deliver permutations of remaining elements, prepended chosen element. after this, repeat element.
so, if have input [0, 1, 2], code uses first element (0) , builds permutations of remaining elements (1 , 2). (these permutations [1, 2] , [2, 1] of course.)
then delivers (yields) 0 prepended [1, 2] , 0 prepended [2, 1], i. e. [0, 1, 2] , [0, 2, 1].
then continues , chooses next element (1). builds permutations of remaining elements (0, 2) (i. e. [0, 2] , [2, 0]).
and forth.
Comments
Post a Comment