Python - All Possible unique K size combinations till N

Python - All Possible unique K size combinations till N

If you're looking to generate all unique combinations of size K from numbers 1 through N, you can utilize the itertools.combinations function.

Problem:

Generate all unique combinations of size K from numbers 1 through N.

Example:

For N = 4 and K = 2:

Expected Output:

[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] 

Solution:

Here's how you can use itertools.combinations:

import itertools def generate_combinations(N, K): return list(itertools.combinations(range(1, N+1), K)) N = 4 K = 2 print(generate_combinations(N, K)) 

Output:

[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] 

Explanation:

  1. The itertools.combinations function generates all possible combinations of the given iterable for a specified length.

  2. range(1, N+1) produces a sequence of numbers from 1 through N.

  3. By specifying K as the second argument to combinations, you get all combinations of size K.

  4. The result from combinations is an iterator, so you might want to convert it to a list (using the list() function) to get the final result.

With this approach, you can easily generate all unique combinations of size K from numbers 1 through N in Python.


More Tags

time-limiting custom-taxonomy numerical pdfminer simple-oauth2 react-intl forms e2e-testing visual-studio-2013 intervention

More Programming Guides

Other Guides

More Programming Examples