This code defines a recursive function called `generate_permutations` that generates...

August 31, 2025 at 01:40 AM

def generate_permutations(elements): """ Recursively generates all possible permutations of a given list of elements. Args: elements (list): The list of elements for which to generate permutations. Returns: list: A list of lists, where each inner list represents a unique permutation. """ if len(elements) == 0: return [[]] # Base case: empty list has one permutation (empty list) first_element = elements[0] remaining_elements = elements[1:] # Recursively get permutations of the remaining elements sub_permutations = generate_permutations(remaining_elements) permutations = [] for sub_perm in sub_permutations: # Insert the first_element into all possible positions within each sub_perm for i in range(len(sub_perm) + 1): new_perm = sub_perm[:] # Create a copy to avoid modifying original new_perm.insert(i, first_element) permutations.append(new_perm) return permutations if __name__ == "__main__": my_list = [1, 2, 3] all_perms = generate_permutations(my_list) print(f"Permutations of {my_list}:") for perm in all_perms: print(perm) another_list = ['A', 'B'] all_perms_str = generate_permutations(another_list) print(f"\nPermutations of {another_list}:") for perm in all_perms_str: print(perm)

This code defines a recursive function called generate_permutations that generates all possible permutations of a given list of elements. Here's a breakdown of what the code does:

Key Functionality

generate_permutations function:

  1. Base case:

    • If the input list (elements) is empty (len(elements) == 0), the function returns [[]], which represents the single permutation of the empty list.
  2. Recursive case:

    • The function takes the first element of the list (first_element) and separates it from the rest (remaining_elements).
    • It then recursively calls itself to generate all permutations of the remaining_elements.
  3. Combining permutations:

    • For each permutation of the remaining_elements (let's call it sub_perm), the first_element is inserted into all possible positions within sub_perm.
    • Each new permutation is added to the permutations list.
  4. Result:

    • The final permutations list, containing all possible unique permutations of the elements, is returned.

Example Code Execution

When my_list = [1, 2, 3]:

  1. Start with elements = [1, 2, 3]. The function will:

    • Extract 1 as first_element.
    • Recursively calculate permutations of [2, 3].
  2. In the recursion for [2, 3]:

    • Extract 2 as first_element, and compute permutations of [3]. This leads to:
      • [3] → sub_permutations = [[3]].
    • Combine 2 with each sub_perm ([3]) to generate:
      • [2, 3] and [3, 2].
  3. Back in the recursion for [1, 2, 3], combine 1 with all permutations of [2, 3] ([[2, 3], [3, 2]]) to generate:

    • [1, 2, 3], [2, 1, 3], [2, 3, 1],
    • [1, 3, 2], [3, 1, 2], [3, 2, 1].

The output for [1, 2, 3] will be:

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

When another_list = ['A', 'B']:

Using the same logic, the output will be:

[['A', 'B'], ['B', 'A']]

Final Output

When the code runs with the sample values, it prints:

Permutations of [1, 2, 3]:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

Permutations of ['A', 'B']:
['A', 'B']
['B', 'A']

Summary

This code generates and prints all possible permutations of a given list of elements (my_list and another_list) using recursive logic.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node