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