Skip to content Skip to sidebar Skip to footer

Generating Binary Numbers Of Size N As Tuples : Itertools.product(*[(0, 1)] * N)

I just found this instruction itertools.product(*[(0, 1)] * n) posted by PAG. Can someone explain how it works? I am trying to find a way of doing permutations without repetitio

Solution 1:

[(0, 1)] is a list of a single tuple of the numbers 0 and 1.

[(0, 1)] * n duplicates the tuple inside of the list, so we get

[(0, 1), (0, 1), ..., (0, 1), (0, 1)]

Then, if we look at the itertools.product function, we want to pass in each of those tuples as single arguments. So, we use the *-operator to unpack our list into arguments to the itertools.product function. So, our function is equivalent to:

itertools.product((0, 1), (0, 1), ..., (0, 1), (0, 1))

which computes all permutations of the n0s and 1s.

Note that itertools.product takes a repeat parameter, which should be used to do this sort of thing:

itertools.product((0, 1), repeat=n)

To do permutations, you can use the itertools.permutations function:

defpick_into_three_bags(n):
    return itertools.permutations(range(n), 3)

Post a Comment for "Generating Binary Numbers Of Size N As Tuples : Itertools.product(*[(0, 1)] * N)"