I am looking for an algorithm that would find all possible combinations of list elements without using itertools. eg. : for [1,2,3,4,5] it prints [[1],[2],[3],[4],[5],[1,2],[1,3],[1,4],[1,5],[2,1].......]
            Asked
            
        
        
            Active
            
        
            Viewed 58 times
        
    0
            
            
        - 
                    Why the restriction against itertools? itertools is a negligible dependency and will probably be faster than any pure-Python solution – Edward Minnix Jul 03 '19 at 12:19
- 
                    Possible duplicate of [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – mbrg Jul 13 '19 at 06:54
1 Answers
0
            
            
        A solution is presented here using recursion.
>>> import copy
>>> def combinations(target,data):
...     for i in range(len(data)):
...         new_target = copy.copy(target)
...         new_data = copy.copy(data)
...         new_target.append(data[i])
...         new_data = data[i+1:]
...         print new_target
...         combinations(new_target,
...                      new_data)
...                      
... 
>>> target = []
>>> data = ['a','b','c','d']
>>> 
>>> combinations(target,data)
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'd']
['a', 'c']
['a', 'c', 'd']
['a', 'd']
['b']
['b', 'c']
['b', 'c', 'd']
['b', 'd']
['c']
['c', 'd']
['d']
 
    
    
        blackbrandt
        
- 2,010
- 1
- 15
- 32
