The string_permutations(s)
function generates all possible permutations of a given string s
and returns them in a sorted list. If the input string is empty, it returns a list containing an empty string, otherwise it recursively generates all permutations of the string.
def string_permutations(s):
"""Find all possible permutations of a string."""
if not s:
return ['']
res = []
for perm in string_permutations(s[1:]):
for i in range(len(perm)+1):
res.append(perm[:i]+s[0]+perm[i:])
return sorted(res)
assert string_permutations('') == ['']
assert string_permutations('abc') == ['abc','acb','bac','bca','cab','cba']
print('All passed!')
python
def string_permutations(s: str) -> list[str]:
"""Find all possible permutations of a string.
Args:
s (str): The input string.
Returns:
list[str]: A list of all possible permutations of the input string.
Example:
>>> string_permutations('')
['']
>>> string_permutations('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
"""
# Base case: if the string is empty, return a list with an empty string
if not s:
return ['']
# Recursive case: get all permutations of the string without the first character
perms = string_permutations(s[1:])
# Initialize an empty list to store the permutations with the first character
res = []
# For each permutation, insert the first character at every possible position
for perm in perms:
for i in range(len(perm) + 1):
# Append the permutation with the first character inserted at position i
res.append(perm[:i] + s[0] + perm[i:])
# Return the sorted list of permutations
return sorted(res)
assert string_permutations('') == ['']
assert string_permutations('abc') == ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
print('All passed!')
string_permutations(s)
Finds all possible permutations of a string s
.
s
: The input string.A sorted list of all possible permutations of the input string.
string_permutations('')
returns ['']
.string_permutations('abc')
returns ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
.