Itertools in Python is a module that produces complex iterators with the help of methods that work on iterators. This module works as a fast, memory-efficient tool that is used either by itself or in combination to form iterator algebra.
Printing Combinations Using itertools
Using Itertools we can display all the possible combinations of the string in a quite optimized way. To display the combination requires 2 parameters. First is the string and the second is the length of substrings needed. The following example makes all combinations for the string ‘abc’ using itertools.
Example:
Python3
# Import combinations from itertools from itertools import combinations def n_length_combo(arr, n): # using set to deal # with duplicates return list (combinations(arr, n)) # Driver Function if __name__ = = "__main__" : arr = 'abc' n = 2 print (n_length_combo([x for x in arr], n) ) |
[('a', 'b'), ('a', 'c'), ('b', 'c')]
Printing Combinations Without using itertools
A. Using recursion
To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.
Python3
# Function to create combinations # without itertools def n_length_combo(lst, n): if n = = 0 : return [[]] l = [] for i in range ( 0 , len (lst)): m = lst[i] remLst = lst[i + 1 :] remainlst_combo = n_length_combo(remLst, n - 1 ) for p in remainlst_combo: l.append([m, * p]) return l # Driver code if __name__ = = "__main__" : arr = "abc" print (n_length_combo([x for x in arr], 2 )) |
[['a', 'b'], ['a', 'c'], ['b', 'a'], ['b', 'c'], ['c', 'a'], ['c', 'b']]
B. By using iterations
In this, return the first combination of n elements from the string as it is, then other combinations are made by considering each element by its position. Each element is treated as unique based on its position, not on its value. So if the input elements are unique, there will be no repeat values in each combination.
Python3
import numpy def n_length_combo(iterable, r): char = tuple (iterable) n = len (char) if r > n: return index = numpy.arange(r) # returns the first sequence yield tuple (char[i] for i in index) while True : for i in reversed ( range (r)): if index[i] ! = i + n - r: break else : return index[i] + = 1 for j in range (i + 1 , r): index[j] = index[j - 1 ] + 1 yield tuple (char[i] for i in index) # Driver code print ([x for x in n_length_combo( "abc" , 2 )]) |
Output:
[('a', 'b'), ('a', 'c'), ('b', 'c')]