Mark W
Mark W

Reputation: 37

Cleaner way to do itertools product combination in Python?

I have the following sample code. I'm prepending a mandatory '1' in front of the generated products. Is there a better way to do it using list generation without using tuple([1]) + a?

from itertools import product

print [tuple([1]) + a for a in list(product([0, 1], repeat=2))]

The output is:

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

Also, what's the best way to get the following result from the above output (Basically, multiplying each value in the tuple by 10^i where i is in respective index and summing that result):

[100, 101, 110, 111]

Upvotes: 0

Views: 401

Answers (4)

user108471
user108471

Reputation: 2607

I'd first create a helper function to handle the numeric joining.

def num_join(*digits):
    return int(''.join(map(str, digits)))

Then just use that in a simplified version of your list comprehension

print [num_join(1, *a) for a in product((0, 1), repeat=2)]

The technique I use to transform a tuple of digits into a number is to simply cast each digit to a string so I can use ordinary string joining, then cast it back into an int. I also remove the redundant list, which is not necessary when we're iterating over the result of product anyway.

Upvotes: -1

Alan
Alan

Reputation: 9620

map(int,("".join(("1",)+x) for x in list(product("01", repeat=2))))

Upvotes: 0

9000
9000

Reputation: 40894

def rawProducts(repeat=2):
  return product([0, 1], repeat=repeat)

def toNumber(seq):
  # here's the trick: the last parameter to reduce() is the initial value;
  # we pretend that we already have a 1 before we started iterating 
  # over seq, instead of prepending the 1 to seq.
  return reduce(lambda acc, x: 10 * acc + x, seq, 1)

result = [toNumber(prod) for prod in rawProducts()]

Will this work for you? BTW works for different values of repeat parameter.

Upvotes: 1

user2357112
user2357112

Reputation: 280778

tuple([1]) is equivalent to just (1,), and you don't need to call list:

print [(1,) + a for a in product([0, 1], repeat=2)]

Upvotes: 1

Related Questions