Solution
Use ‘itertools.permutations()’ function to find the permutation of a list of strings in Python. The following code will help you:
from itertools import permutations def find_permutations(strings): # Generate permutations of the strings permuted_strings = permutations(strings) # Convert permutations generator to a list of tuples permuted_strings = list(permuted_strings) # Convert tuples to lists permuted_strings = [list(p) for p in permuted_strings] return permuted_strings # Example usage strings = ["apple", "banana", "orange"] permutations_list = find_permutations(strings) for permuted_string in permutations_list: print(permuted_string) |
You will get all possible permutation outputs of the string inputs. Moreover, the number of permutations grows exponentially with the size of inputs, so be cautious while you give large inputs.
If you want to find permutations with repetition (i.e., allowing repeated elements in the permutations), you can use ‘itertools.product()’ instead of ‘itertools.permutations()’.
Suggested blogs:
>>How to manage the Text in the container in Django?
>>Activating Virtual environment in visual studio code windows 11
>>Fix webapp stops working issue in Django- Python webapp
>>Creating a form in Django to upload a picture from website
>>Sending Audio file from Django to Vue
>>How to keep all query parameters intact when changing page in Django?
>>Solved: TaskList View in Django