Write a Python program to generate the combinations of n distinct objects taken from the elements of a given list. Example: Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9] Combinations of 2 distinct objects: [1, 2] [1, 3] [1, 4] [1, 5] .... [7, 8] [7, 9] [8, 9]
Write a Python program to generate the combinations of n distinct objects taken from the
elements of a given list. Example: Original list: [1, 2, 3, 4, 5, 6, 7, 8, 9] Combinations of 2 distinct
objects: [1, 2] [1, 3] [1, 4] [1, 5] .... [7, 8] [7, 9] [8, 9]
import itertools
def generate_combinations(original_list, n):
"""
Generates all combinations of n distinct objects from a given list.
Args:
original_list: The list of elements to draw from.
n: The number of elements in each combination.
Returns:
A list of tuples, where each tuple is a combination.
"""
# Use itertools.combinations to generate the combinations
combinations_iterator = itertools.combinations(original_list, n)
# Convert the iterator to a list for easier viewing/processing
return list(combinations_iterator)
# Example usage:
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 2
# Generate and print the combinations
combinations = generate_combinations(original_list, n)
print(f"Original list: {original_list}")
print(f"Number of objects in each combination: {n}")
print("Combinations:")
for combo in combinations:
print(list(combo)) # Convert tuple to list for output format consistency with the example
Comments
Post a Comment