Given an array of size n, generate and print all possible combinations of r elements in array. Examples:
Input : arr[] = [1, 2, 3, 4],
r = 2
Output : [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
This problem has existing recursive solution please refer Print all possible combinations of r elements in a given array of size n link. We will solve this problem in python using itertools.combinations() module.
What does itertools.combinations() do ?
It returns r length subsequences of elements from the input iterable. Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.
- itertools.combinations(iterable, r) : It return r-length tuples in sorted order with no repeated elements. For Example, combinations(‘ABCD’, 2) ==> [AB, AC, AD, BC, BD, CD].
- itertools.combinations_with_replacement(iterable, r) : It return r-length tuples in sorted order with repeated elements. For Example, combinations_with_replacement(‘ABCD’, 2) ==> [AA, AB, AC, AD, BB, BC, BD, CC, CD, DD].
Python3
from itertools import combinations
def rSubset(arr, r):
return list(combinations(arr, r))
if __name__ == "__main__":
arr = [1, 2, 3, 4]
r = 2
print (rSubset(arr, r))
|
Output
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
01 Aug, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...