Reputation: 194
My approach to the problem was as follows-
a=[ ]
for i in range(7):
a.append([0]*7)
c=dict()
for i in range(7):
for j in range(7):
a[i][j]=(i,j)
for i in range(7):
for j in range(7):
c[i+j]=tuple((i*j+j+c))
print c
But this produces:
{0: (0, 0), 1: (1, 0), 2: (2, 0), 3: (3, 0), 4: (4, 0), 5: (5, 0), 6: (6, 0), 7: (6, 1), 8: (6, 2), 9: (6, 3), 10: (6, 4), 11: (6, 5), 12: (6, 6)}
Upvotes: 1
Views: 78
Reputation: 4449
Using some standard Python utilities:
from collections import defaultdict
from itertools import product
All numbers on a single dice:
numbers = range(1,7)
And now, for each combination, sum the combination and append the combination to the list for that combination:
reduce(lambda acc, comb: acc[sum(comb)].append(comb) or acc, product(numbers, numbers), defaultdict(list))
Resulting in:
defaultdict(<type 'list'>, {2: [(1, 1)], 3: [(1, 2), (2, 1)], 4: [(1, 3), (2, 2), (3, 1)], 5: [(1, 4), (2, 3), (3, 2), (4, 1)], 6: [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)], 7: [(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1)], 8: [(2, 6), (3, 5), (4, 4), (5, 3), (6, 2)], 9: [(3, 6), (4, 5), (5, 4), (6, 3)], 10: [(4, 6), (5, 5), (6, 4)], 11: [(5, 6), (6, 5)], 12: [(6, 6)]})
Upvotes: 0
Reputation: 117981
A step by step way to do this would be
pairs = {}
for first in range(1,7):
for second in range(1,7):
total = first + second
if total in pairs:
# If sum exists, add this tuple to the list for this key.
pairs[total] += [(first,second)]
else:
# If sum doesn't exist, start a new list for this key
pairs[total] = [(first,second)]
Result
>>> pairs
{2: [(1, 1)],
3: [(1, 2), (2, 1)],
4: [(1, 3), (2, 2), (3, 1)],
5: [(1, 4), (2, 3), (3, 2), (4, 1)],
6: [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)],
7: [(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1)],
8: [(2, 6), (3, 5), (4, 4), (5, 3), (6, 2)],
9: [(3, 6), (4, 5), (5, 4), (6, 3)],
10: [(4, 6), (5, 5), (6, 4)],
11: [(5, 6), (6, 5)],
12: [(6, 6)]}
Since this sounds like an academic exercise I assume you cannot use some of the pre-existing Python modules. Otherwise, you may want to check out collections.defaultdict and itertools.product. The former can handle the "does this key exist yet or not?" and the latter can handle combinations to remove your nested for
loops.
Upvotes: 2
Reputation: 7555
This will work:
combinations = {}
for a in range(1, 7):
for b in range(1, 7):
combinations.setdefault(a+b, []).append((a, b))
Result:
{2: [(1, 1)],
3: [(1, 2), (2, 1)],
4: [(1, 3), (2, 2), (3, 1)],
5: [(1, 4), (2, 3), (3, 2), (4, 1)],
6: [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)],
7: [(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1)],
8: [(2, 6), (3, 5), (4, 4), (5, 3), (6, 2)],
9: [(3, 6), (4, 5), (5, 4), (6, 3)],
10: [(4, 6), (5, 5), (6, 4)],
11: [(5, 6), (6, 5)],
12: [(6, 6)],
}
Upvotes: 1