質問の小町算の類題をPythonで解いてみた。

 質問の小町算の類題Pythonで解いてみました。回答者さんの回答を参考にさせていただきました。(^_^;
 面白い問題でしたが、存在に気づきませんでした。ひょんなことから見つけて、ちょっとPythonでプログラムを作りたくなってしまいました。(^_^;

●KomachiSim.py

# KomachiSim.py
import itertools
from time import time
tm=time()  # Timer Start
n="123456789"
for i in itertools.combinations([1,2,3,4,5,6,7,8],3):
  for o in itertools.product('+-*/',repeat=3):
    expr=n[:i[0]]+o[0]+n[i[0]:i[1]]+o[1]+n[i[1]:i[2]]+o[2]+n[i[2]:]
    expr=expr.replace('/','.0/')
    if eval(expr)==100.0 :
      print(expr+"=100")
tm=time()-tm  # Timer Stop
print("Runtime : %.3f [sec]"%tm)

●実行結果

123-45-67+89=100
Runtime : 0.109 [sec]

※参考URL
たのしいPython 組み合わせと順列
10.1. itertools ー 効率的なループ実行のためのイテレータ生成関数
文字列操作の比較表: Ruby, Python, JavaScript, Perl, C++ - bkブログ

みんなのPython 第3版

みんなのPython 第3版

Pythonスタートブック

Pythonスタートブック

初めてのPython 第3版

初めてのPython 第3版