こんにちは、
最初
[式 for 要素 in リスト] <-- (1)
の機能(とアルゴリズム...)が分からず、帰った後ずっと考えてました。
dice2.py -- 自分の好み(というか脳力)で省略していない箇所あり
dice4.py -- 合計値が同じになる場合を考慮。
(同じ数字が使われる可能性は考えていない)
dice1.py -- (1)を理解するために作成したもの
という感じです
でわでわ
-- ぬ
--^ dice2.py
def do(list):
sum = [0]
str = ['']
for n in list:
sum = [x + 0 for x in sum] + [x + n for x in sum]
str = ['%s '%(x,) for x in str] + ['%s+%d'%(x,n) for x in str]
for i in xrange(len(sum)):
print '%3d = %s'%(sum[i],str[i])
if __name__ == '__main__':
num = [1,2,4,8]
do(num)
--$
--^ dice4.py
def do(list):
sum = [0]
form = [[]]
for n in list:
sum += [x + n for x in sum ]
form += [x + [str(n)] for x in form]
tbl = {}
for i in xrange(len(sum)):
tbl[sum[i]] = tbl.get(sum[i],[])+[form[i]]
for n in tbl.keys():
print '%3d --> %s'%(n,','.join(['['+','.join(e)+']' for e in tbl[n]]))
if __name__ == '__main__':
num = [1,2,3,4]
do(num)
--$
--^ dice1.py
def do(list):
sum = [0]
str = ['']
for n in list:
sum0 = []
for base in sum:
sum0 = sum0 + [base+n]
sum = sum + sum0
str0 = []
str1 = []
for base in str:
str0 = str0 + ['%s ' %(base,)]
str1 = str1 + ['%s+%d'%(base,n)]
str = str0 + str1
for i in xrange(len(sum)):
print '%3d = %s'%(sum[i],str[i])
if __name__ == '__main__':
num = [1,2,4,8]
do(num)
--$