Return a generator of all the permutations of the string.
(str_)
| 13 | import unittest |
| 14 | |
| 15 | def permutations(str_): |
| 16 | """ Return a generator of all the permutations of the string. """ |
| 17 | |
| 18 | # A string such as 'a' has itself as its only permutation, while for 'ab' |
| 19 | # the permutations are 'ab' and 'ba'. For 'abc', a three-character string, |
| 20 | # there are six permutations: 'abc', 'acb', 'bac', 'bca', 'cab', 'cba'. Two |
| 21 | # of these permutations, 'abc' and 'acb', start with 'a', and what follows |
| 22 | # this first character is, respectively, 'bc' and 'cb': the two possible |
| 23 | # permutations of 'cb'. This allows us to see the pattern here: for each |
| 24 | # letter in the string we need to concatenate to it the sub-permutations |
| 25 | # that can be generated when the letter is removed from the string. |
| 26 | |
| 27 | if len(str_) == 1: |
| 28 | yield str_ |
| 29 | |
| 30 | for index, letter in enumerate(str_): |
| 31 | # The string without the index-th letter |
| 32 | without = str_[:index] + str_[index + 1:] |
| 33 | for sub_permutation in permutations(without): |
| 34 | yield letter + sub_permutation |
| 35 | |
| 36 | class PermutationsTest(unittest.TestCase): |
| 37 |
no outgoing calls