Reputation: 37
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
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
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
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