Sometimes, while working with Python domain, we can have a problem in which we need to produce various combination of elements. This can be K sized unique combinations till N. This problem can have application in data domains and school programming. Let’s discuss certain ways in which this task can be performed.
Input : N = 2, K = 3 Output : [(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)] Input : N = 4, K = 2 Output : [(0, 0), (0, 1), (0, 2), (0, 3), (1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
Method #1 : Using product() + setdefault() + loop The combination of above functions offers an approach to this problem. In this, we use product to perform all combinations and eliminate duplicates using setdefault() and loop by brute force approach.
Python3
from itertools import product
N = 4
K = 3
temp = list (product( range (N), repeat = K))
res = {}
for tup in temp:
key = tuple ( sorted (tup))
res.setdefault(key, []).append(tup)
res = list (res.keys())
print ("The unique combinations : " + str (res))
|
Output : The unique combinations : [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 2), (0, 2, 3), (0, 3, 3), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)]
Method #2 : Using combinations_with_replacement() This offers an alternative method to solve this problem. This function performs internally, all that is required to get to solution.
Python3
from itertools import product, combinations_with_replacement
N = 4
K = 3
res = list (combinations_with_replacement( range (N), K))
print ("The unique combinations : " + str (res))
|
Output : The unique combinations : [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 2), (0, 2, 3), (0, 3, 3), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)]
Method 3:Using Nested Loops.
Algorithm:
- Initialize an empty list called “res”.
- Using nested loops, generate all possible unique combinations of 3 integers within the range of 0 to N-1 (inclusive).
- Append each combination to the “res” list.
- Print the resulting list.
Python3
N = 4
K = 3
res = []
for i in range (N):
for j in range (i, N):
for k in range (j, N):
res.append((i, j, k))
print ( "The unique combinations : " + str (res))
|
OutputThe unique combinations : [(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 2), (0, 2, 3), (0, 3, 3), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)]
The time complexity of the algorithm is O(N^3) because there are three nested loops that each iterate over N values.
The space complexity is O(N^3) because the resulting list “res” will contain N^3 tuples.