Combinations in Python without using itertools - GeeksforGeeks

22 Oct, 2021
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 themselves or in combination to form iterator algebra. 
Using Itertools we can display all the possible combinations of the string in a quite optimized way. To display the combination, it requires 2 parameters. First is the string and second is the length of substrings needed. The following example makes all combinations for the string ‘abc’ using itertools. Example: 
Python3
# Import combinations from itertoolsfrom itertools import combinations        def n_length_combo(arr, n):         # using set to deal    # with duplicates     return list(combinations(arr, n))   # Driver Functionif __name__ == "__main__":    arr = 'abc'    n = 2    print (n_length_combo([x for x in arr], n) )
Output
[('a', 'b'), ('a', 'c'), ('b', 'c')]
By 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 itertoolsdef n_length_combo(lst, n):         if n == 0:        return [[]]         l =[]    for i in range(0, len(lst)):                 m = lst[i]        remLst = lst[i + 1:]                 for p in n_length_combo(remLst, n-1):            l.append([m]+p)                 return l # Driver codeif __name__=="__main__":    arr ="abc"    print(n_length_combo([x for x in arr], 2))
Output 
[('a', 'b'), ('a', 'c'), ('b', 'c')]
By using iterationsIn 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 codeprint([x for x in n_length_combo("abc", 2)])
Output 
[('a', 'b'), ('a', 'c'), ('b', 'c')]
adnanirshad158
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python