Skip to content
Related Articles

Related Articles

Improve Article

Combinations in Python without using itertools

  • Last Updated : 27 Feb, 2020

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.

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, 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:




# 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) )

Output

[('a', 'b'), ('a', 'c'), ('b', 'c')]

Printing Combinations Without using itertools

  • 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.






    # 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:]
              
            for p in n_length_combo(remLst, n-1):
                l.append([m]+p)
                  
        return l
      
    # Driver code
    if __name__=="__main__":
        arr ="abc"
        print(n_length_combo([x for x in arr], 2))

    Output

    [('a', 'b'), ('a', 'c'), ('b', 'c')]
    
  • 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.




    import numpy
      
      
    def n_length_combo(iterable, r):
          
        char = tuple(iterable)
        n = len(char)
          
        if r > n:
            return
          
        index = numpy.arange(r)
          
        # retruns 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')]
    

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :