  Python itertools.combission () module for printing all possible combinations

Python Methods and Functions

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 a recursive solution. See size n . We'll solve this problem in python with using the itertools.combination () module.

What does itertools.combination () do?

It returns r subsequences of elements from input iterations. Combinations are presented in lexicographic sorting order. Thus, if the input iterable is sorted, the combined tuples will be created in sorted order.

• itertools.combination (iterable, r):
It returns r-length tuples in sorted order with no duplicate elements. For example, combinations (& # 39; ABCD & # 39 ;, 2) == & gt; [AB, AC, AD, BC, BD, CD].
• itertools.combination_with_replacement (iterable, r):
It returns r-length tuples in sorted order with repeating elements. For example, combinations_with_replacement (& # 39; ABCD & # 39 ;, 2) == & gt; [AA, AB, AC, AD, BB, BC, BD, CC, CD, DD].
•  # A function that returns a subset or length of r from n from itertools import combinations   def rSubset (arr, r):   # return a list of all subsets of length r # to work with duplicate subsets # set (list (combinations (arr, r))) return   list (combinations (arr, r))   # Driver function 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]]

This article courtesy of Shashank Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.