0

私はこれをほぼ完了しましたが、コードが機能せず、理由がわかりません:

dice1 = 1
listofallcombinations = []
while dice <= 6:
    dice2 = 1
    while dice2 <= 6:
         listofallcombinations.append((dice1,dice2))
         dice2 = dice2 + 1
    dice1 = dice1 + 1

sumof2dice = []
sumation = 2
while sumation <= 12:
    sumof2dice[str(sumation)] = []
    sumation = sumation + 1

for i in listofallcombinations:
    sumofdice = 2
    while sumofdice <= 12:
        if i[0] + i[1] == sumofdice:
            sumof2dice{str{sumofdice)).append(i)
        sumofdice = sumofdice + 1


for i in sumof2dice
    print i, "\n", sumof2dice[i], "\n"

次のエラーが表示されます。

sumof2dice{str{sumofdice)).append(i)

に構文エラーがありますが、修正方法がわかりません。

ありがとう!

4

2 に答える 2

3

コードを改善することもできます。

>>> from collections import Counter
>>> listofall = []
>>> for i in range(1,7):
    for j in range(1,7):
        listofall.append(i+j)


>>> Counter(listofall)
Counter({7: 6, 6: 5, 8: 5, 5: 4, 9: 4, 4: 3, 10: 3, 3: 2, 11: 2, 2: 1, 12: 1})

別の出力が必要であることを理解すると、次のように実現できます。

>>> listofall = dict((i, []) for i in range(2,13))
>>> for i in range(1,7):
    for j in range(1,7):
        listofall[i+j].append((i,j))

>>> listofall
{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)]}
于 2013-11-05T09:17:51.900 に答える
1

あなたはおそらくしたいです

sumof2dice = {}

リストの代わりに。

コード内のさまざまな構文エラーを修正しました。

dice1 = 1 = []
while dice1 <= 6:
    dice2 = 1
    while dice2 <= 6:
         listofallcombinations.append((dice1,dice2))
         dice2 = dice2 + 1
    dice1 = dice1 + 1

sumof2dice = {}
sumation = 2
while sumation <= 12:
    sumof2dice[str(sumation)] = []
    sumation = sumation + 1

for i in listofallcombinations:
    sumofdice = 2
    while sumofdice <= 12:
        if i[0] + i[1] == sumofdice:
            sumof2dice[str(sumofdice)].append(i)
        sumofdice = sumofdice + 1


for i, s in sumof2dice.items():
    print i, s

出力:

11 [(5, 6), (6, 5)]
10 [(4, 6), (5, 5), (6, 4)]
12 [(6, 6)]
3 [(1, 2), (2, 1)]
2 [(1, 1)]
5 [(1, 4), (2, 3), (3, 2), (4, 1)]
4 [(1, 3), (2, 2), (3, 1)]
7 [(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1)]
6 [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]
9 [(3, 6), (4, 5), (5, 4), (6, 3)]
8 [(2, 6), (3, 5), (4, 4), (5, 3), (6, 2)]
于 2013-11-05T09:04:59.373 に答える