6□4□5□2□1の□に+-×÷を入れて0〜35を作る問題をPythonで解いてみよう。まずは集合を使ってみる。
ex = ["6", "", "4", "", "5", "", "2", "", "1"] op = ["+", "-", "*", "/"] s = set() for i in op: ex[1] = i for j in op: ex[3] = j for k in op: ex[5] = k for l in op: ex[7] = l e = "".join(ex) v = eval(e) if int(v) == v: s.add(int(v)) s
{-35, -34, -33, ……中略…… 239, 240, 241}
集合でなく辞書にしてみよう。s = set()
を d = {}
にして、最後の s.add(int(v))
を d[int(v)] = e
にする。
sorted(d.items())
[(-35, '6-4*5*2-1'), (-34, '6-4*5*2/1'), (-33, '6-4*5*2+1'), ……中略…… (0, '6/4-5/2+1'), (1, '6+4-5*2+1'), (2, '6+4-5-2-1'), (3, '6/4+5/2-1'), (4, '6/4+5/2/1'), (5, '6/4+5/2+1'), (6, '6-4+5-2+1'), (7, '6+4-5+2/1'), (8, '6-4+5+2-1'), (9, '6-4+5+2/1'), (10, '6-4+5+2+1'), (11, '6-4+5*2-1'), (12, '6-4+5*2/1'), (13, '6*4-5*2-1'), (14, '6/4*5*2-1'), (15, '6/4*5*2/1'), (16, '6/4*5*2+1'), (17, '6*4-5-2/1'), (18, '6*4-5-2+1'), (19, '6+4+5*2-1'), (20, '6*4-5+2-1'), (21, '6*4-5+2/1'), (22, '6*4-5+2+1'), (23, '6+4*5-2-1'), (24, '6+4*5-2/1'), (25, '6+4*5-2+1'), (26, '6*4+5-2-1'), (27, '6*4+5-2/1'), (28, '6*4+5-2+1'), (29, '6+4*5+2+1'), (30, '6*4+5+2-1'), (31, '6*4+5+2/1'), (32, '6*4+5+2+1'), (33, '6*4+5*2-1'), (34, '6*4+5*2/1'), (35, '6*4+5*2+1'), ……中略…… (239, '6*4*5*2-1'), (240, '6*4*5*2/1'), (241, '6*4*5*2+1')]