Permutations
# Function to generate permutations
def generate_permutations(elements):
# Base case: if there's only one element, return it as a single permutation
if len(elements) == 1:
return [elements]
# List to store permutations
permutations = []
# Generate permutations for each element in the list
for i in range(len(elements)):
# Take the current element as the first element
current = elements[i]
# Generate permutations for the remaining elements
remaining = elements[:i] + elements[i+1:]
for permutation in generate_permutations(remaining):
# Add the current element to the front of each permutation
permutations.append([current] + permutation)
return permutations
# Test the permutation function
my_elements = [1, 2, 3]
result = generate_permutations(my_elements)
print(result)
Explanation: In this example, we define a function generate_permutations
that takes a list of elements as input. This function uses recursion to generate permutations by considering each element as the first element and recursively generating permutations for the remaining elements.
The function starts with a base case: if there's only one element, it returns it as a single permutation. Otherwise, it initializes an empty list called permutations
to store all the generated permutations.
Next, it loops through each element in the list and considers it as the first element. It then generates permutations for the remaining elements by removing the current element from the list and recursively calling the generate_permutations
function on the updated list.
For each generated permutation, it appends the current element to the front of the permutation and adds it to the permutations
list.
Finally, it returns the permutations
list containing all the generated permutations.
When we test the permutation function with my_elements = [1, 2, 3]
, it generates all possible permutations of these elements and stores them in the result
list, which is then printed.