「笑わない数学者-MATHEMATICAL GOODBYE」の問題をPythonで解いてみた。

 「笑わない数学者-MATHEMATICAL GOODBYE」の問題をPythonで解いてみました。(^_^;
 昔作ったプログラムの有り合せでなんとなく出来てしまいました。(^_^;

● MathematicalGoodbye.py

# coding: UTF-8
# MathematicalGoodbye.py

import itertools
from time import time

def main():
    tm=time()  # Timer Start

    BALL = list(range(1,15+1))
    SN21 = list(range(1,21+1))

    for p in itertools.permutations(BALL,5):
        a,b,c,d,e = p
        m = [a,b,c,d,e,
            a+b,b+c,c+d,d+e,e+a,
            a+b+c,b+c+d,c+d+e,d+e+a,e+a+b,
            a+b+c+d,b+c+d+e,c+d+e+a,d+e+a+b,e+a+b+c,
            a+b+c+d+e]

        # 1〜21までちゃんと揃っているか調べる
        if sorted(m)!=SN21: continue
        # チェックを潜り抜けたものだけを出力
        print((a,b,c,d,e))

    tm=time()-tm  # Timer Stop
    print("Runtime : %.3f [sec]"%tm)

if __name__ == '__main__':
    main()

●実行結果

(1, 3, 10, 2, 5)
(1, 5, 2, 10, 3)
(2, 5, 1, 3, 10)
(2, 10, 3, 1, 5)
(3, 1, 5, 2, 10)
(3, 10, 2, 5, 1)
(5, 1, 3, 10, 2)
(5, 2, 10, 3, 1)
(10, 2, 5, 1, 3)
(10, 3, 1, 5, 2)
Runtime : 2.263 [sec]

笑わない数学者 MATHEMATICAL GOODBYE (講談社文庫)

笑わない数学者 MATHEMATICAL GOODBYE (講談社文庫)