To find all possible permutations of a given string in Python, you can use the permutations()
function from the itertools
module or implement a recursive solution. Here’s an example for both approaches:
- Using the
permutations()
function:
from itertools import permutations
def find_permutations(string):
perms = permutations(string)
return [''.join(perm) for perm in perms]
input_string = "abc"
permutations_list = find_permutations(input_string)
for perm in permutations_list:
print(perm)
Output:
abc
acb
bac
bca
cab
cba
In this example, we define a function find_permutations()
that takes a string as input. We use the permutations()
function from the itertools
module to generate all possible permutations of the characters in the string. We then join each permutation into a string using ''.join(perm)
and store them in a list.
Finally, we iterate over the permutations list and print each permutation.
- Using a recursive solution:
def find_permutations(string):
if len(string) == 1:
return [string]
perms = []
for i in range(len(string)):
first_char = string[i]
remaining_chars = string[:i] + string[i+1:]
for perm in find_permutations(remaining_chars):
perms.append(first_char + perm)
return perms
input_string = "abc"
permutations_list = find_permutations(input_string)
for perm in permutations_list:
print(perm)
Output:
abc
acb
bac
bca
cab
cba
In this example, we define a recursive function find_permutations()
that takes a string as input. The base case occurs when the string has only one character, in which case we simply return a list containing that character.
For larger strings, we iterate over each character of the input string and generate all possible permutations of the remaining characters by recursively calling the find_permutations()
function on the remaining characters. We then combine the first character with each of the recursive permutations and add them to the perms
list.
Finally, we return the perms
list containing all the permutations.
Both approaches yield the same output, which is a list of all possible permutations of the given string.
Note that the number of permutations grows rapidly with the length of the input string. For long strings, the number of permutations can become very large, leading to longer processing times and increased memory usage.
+ There are no comments
Add yours