from itertools import combinationsdef n_length_combo(arr, n):# using set to deal# with duplicates return list(combinations(arr, n))# Driver Function
if __name__ == "__main__":arr = '01'n = 3print (n_length_combo([x for x in arr], n) )
Expected Output
wanted 3 combination of 0 and 1 .Tried with above example but it is not working
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 productitems = [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)