33. All the permutations
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:
aabhas 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
word = "abc"["abc", "acb", "bac", "bca", "cab", "cba"]Example 2
word = "aab"["aab", "aba", "baa"]Example 3
word = ""[""]Constraints
wordhas 0 to 6 letters, all lower case.
Submit also runs 5 more tests you can't see.
Practises Recursion (lesson 20).
- Think recursively: every ordering starts with one of the letters, followed by an ordering of the letters left over.
- For each position
i, takeword[i]first and callpermutations(word[:i] + word[i + 1:])for the rest. The base case: a word of 0 or 1 letters has one ordering, itself, so return[word]; for""that is[""]. - Repeated letters make the same ordering more than once: collect the results in a set to drop the repeats, then
return sorted(found).
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.