MCPcopy Create free account
hub / github.com/careercup/ctci / permutations

Function permutations

python/Chapter 9/Question9_05/permutations.py:15–34  ·  view source on GitHub ↗

Return a generator of all the permutations of the string.

(str_)

Source from the content-addressed store, hash-verified

13import unittest
14
15def 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
36class PermutationsTest(unittest.TestCase):
37

Callers 1

test_permutationsMethod · 0.85

Calls

no outgoing calls

Tested by 1

test_permutationsMethod · 0.68