Given an array of size n, generate and print all possible combinations of r elements in array.
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].
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Python program to print Calendar without calendar or datetime module
- Iterative approach to print all combinations of an Array
- Print all the combinations of N elements by changing sign such that their sum is divisible by M
- Python | Dictionary key combinations
- Combinations in Python without using itertools
- Python - Get all numbers combinations in list
- Python - Itertools Combinations() function
- Python - Nested dictionary Combinations
- Python | Pair Product combinations
- Python - Dictionary Key Value lists combinations
- Python - All pair combinations of 2 tuples
- Python - Dual element Rows Combinations
- Python | Size Range Combinations in list
- Python - All Possible unique K size combinations till N
- Python program to get all unique combinations of two Lists
- Python - Odd or Even elements combinations Summations in Matrix
- Python - Combinations of sum with tuples in tuple list
- Python | Combinations of elements till size N in list
- Python | Find Mixed Combinations of string and list
- pwd module in Python