Python Program to Compute all the Permutation of the String
ⓘ Sponsored by 10xer.co
A permutation of a string is a rearrangement of its characters that creates a new string. For example, the permutations of the string “ABC” are “ABC”, “ACB”, “BAC”, “BCA”, “CAB”, and “CBA”.
Python Code :
The Below Python program uses recursion to compute all the permutations of a given string:
def get_permutations(string):
"""
Returns a list of all possible permutations of the given string.
"""
# Base case: if the string is empty, there is only one permutation: the empty string
if len(string) == 0:
return ['']
# Otherwise, find the permutations of the string without its first character
smaller_permutations = get_permutations(string[1:])
# Insert the first character of the original string into every possible position
permutations = []
for perm in smaller_permutations:
for i in range(len(perm) + 1):
permutations.append(perm[:i] + string[0] + perm[i:])
return permutations
You can use this function by passing in a string as an argument, like this:
print(get_permutations('abc'))
This will output a list of all the possible permutations of the string ‘abc’:
['abc', 'bac', 'bca', 'acb', 'cab', 'cba']
ⓘ Sponsored by 10xer.co