150 XP

33. All the permutations

Expert backtracking recursion strings

A permutation of a word is one way of ordering all its letters. abc has six: abc, acb, bac, bca, cab and cba.

Write a function permutations(word) that takes a word and returns a list of all its different permutations, as strings, sorted in alphabetical order. Write it yourself, with recursion: don't use the itertools module.

  • When a letter repeats, some orderings come out the same. List each one only once: aab has three permutations, not six.
  • A word with one letter has one permutation: itself.
  • The empty word "" has one permutation too, the empty word: return [""].

Example 1

Inputword = "abc"
Output["abc", "acb", "bac", "bca", "cab", "cba"]
ExplanationEvery order of a, b and c.

Example 2

Inputword = "aab"
Output["aab", "aba", "baa"]
ExplanationSwapping the two a's gives the same word.

Example 3

Inputword = ""
Output[""]
ExplanationThe empty word has one ordering: itself.

Constraints

  • word has 0 to 6 letters, all lower case.

Submit also runs 5 more tests you can't see.

Practises Recursion (lesson 20).

Code
def permutations(word):
    """List every different ordering of a word's letters.

    word: str, 0 to 6 lower-case letters
    Returns: list of str, each different ordering once,
        in alphabetical order
    """
    # Write your code here
    pass