Search code examples
pythoncombinationspermutation

Getting all possible combination for [1,0] with length 3 [0,0,0] to [1,1,1]


    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 = '01'
    n = 3
    print (n_length_combo([x for x in arr], n) )

Expected Output

enter image description here

wanted 3 combination of 0 and 1 .Tried with above example but it is not working


Solution

  • You're looking for a Cartesian product, not a combination or permutation of [0, 1]. For that, you can use itertools.product.

    from itertools import product
    
    items = [0, 1]
    
    for item in product(items, repeat=3):
        print(item)
    

    This produces the output you're looking for (albeit in a slightly different order):

    (0, 0, 0)
    (0, 0, 1)
    (0, 1, 0)
    (0, 1, 1)
    (1, 0, 0)
    (1, 0, 1)
    (1, 1, 0)
    (1, 1, 1)