2015-02-11 90 views
1

一個令人困惑的任務

我對這個問題的方法是如下 -

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 

但是,這會產生:

{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)} 

回答

2

一步一步的方式做到這一點會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)] 

結果

>>> 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)]} 

由於這聽起來像一個學術活動我假設你不能使用一些預先存在的Python模塊。否則,您可能想要查看collections.defaultdictitertools.product。前者可以處理「這個鍵是否存在?」後者可以處理組合來刪除嵌套的for循環。

+0

我不想概率先生。我想要在字典中的組合......請再讀一遍這個問題再次!!!! – 2015-02-11 13:56:15

+5

看我的編輯。冷靜下來,你不需要輸入全部大寫或使用!!!!!在你的句子上。放鬆,請冷靜地問你的問題和意見。 – CoryKramer 2015-02-11 13:59:54

+0

對不起Cyber​​ ...我明天考試,所以我恐慌.....感謝您的明確和完美的答案:) – 2015-02-11 14:02:29

1

這將工作:

combinations = {} 
for a in range(1, 7): 
    for b in range(1, 7): 
     combinations.setdefault(a+b, []).append((a, b)) 

結果:

{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)], 
} 
0

使用一些標準的Python實用程序:

from collections import defaultdict 
from itertools import product 

所有數字在單一骰子:

numbers = range(1,7) 

而現在,每個組合,總結了組合和組合追加到列表中該組合:

reduce(lambda acc, comb: acc[sum(comb)].append(comb) or acc, product(numbers, numbers), defaultdict(list)) 

結果造成:

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)]})