Advanced · Recursion · 162 of 264
Permutations
Print every different ordering of the letters of a word, in alphabetical order, each once (the word may repeat letters). Write the recursion yourself.
Input: a word of at most 7 letters. Output: the orderings, one per line.
Examples
Input
abc
Output
abc acb bac bca cab cba
Input
a
Output
a
Input
aab
Output
aab aba baa
One more test checks other inputs when you press Check.
Stuck? The idea behind recursion
A recursive function calls itself on a smaller version of the problem, until it reaches a case small enough to answer directly (the base case).
Trust the smaller call to be right, and only work out how to build this answer from it.
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))Watch for: Without a base case, or if the problem doesn't get smaller, it never stops: Python gives up with a RecursionError.