Reputation: 29977
I have a dict for which I would like to find all combinations of sums of values, multiplied by an increasing factor. A possible code for the case where the size of the dict is 2:
# data and n come from elsewhere
data = {'a': 1, 'b': 2}
n = 3
for x in xrange(0, n):
for y in xrange(0, n):
print("{0} * {1} + {2} * {3} = {4}".format(x, data['a'], y, data['b'], x * data['a'] + y * data['b']))
which gives
0 * 1 + 0 * 2 = 0
0 * 1 + 1 * 2 = 2
0 * 1 + 2 * 2 = 4
1 * 1 + 0 * 2 = 1
(...)
2 * 1 + 2 * 2 = 6
The problem I have is that the number of elements in the dict will vary, so the number of nested for
should be changing as well. Is there a better way to code such a problem to accommodate such a variable dict?
Upvotes: 0
Views: 76
Reputation: 304137
You can replace your nested loop with a single loop over the cartesian product
from itertools import product
for x, y in product(range(n), repeat=2):
...
This isn't too useful in itself as you still hardcode 2 variables in there. But it leads us on the the next point - itertools.product
yields tuples as you iterate over it
from itertools import product
num_loops = 5 # len(data) in your case
for item in product(range(n), repeat=num_loops):
... # item is a 5-tuple
Upvotes: 2