1~9の4つの組合せの四則計算

0を除いた組合せ

import itertools

seq = range(1, 10)

# 組合せ
data = list(itertools.combinations(seq, 4))

print(len(data))
# 126
import itertools

def test_eval(s):

    try:
        r = eval(s)
    except ZeroDivisionError:
        r = None

    if r == 10:
        print(s)
        return True
    else:
        return False

seq = range(1, 10)

data = [i for i in itertools.permutations(seq, 4)]

print(len(data))

# print(data)

calc = [j for j in itertools.product("+-*/", repeat=3)]

result = []

for d in data:

    for c in calc:
        t1 = f"{d[0]} {c[0]} {d[1]} {c[1]} {d[2]} {c[2]} {d[3]}"

        if test_eval(t1):
            result.append(tuple(sorted(list(d))))

        t2 = f"( {d[0]} {c[0]}  {d[1]} {c[1]} {d[2]} ) {c[2]} {d[3]} "

        if test_eval(t2):
            result.append(tuple(sorted(list(d))))

        t3 = f"{d[0]} {c[0]} ( {d[1]} {c[1]} {d[2]} {c[2]} {d[3]} )"

        if test_eval(t3):
            result.append(tuple(sorted(list(d))))

        t4 = f"( {d[0]} {c[0]} {d[1]} ) {c[1]} ( {d[2]} {c[2]} {d[3]} )"

        if test_eval(t4):
            result.append(tuple(sorted(list(d))))

        t5 = f"{d[0]} {c[0]} ( {d[1]} {c[1]} {d[2]} ) {c[2]} {d[3]}"

        if test_eval(t5):
            result.append(tuple(sorted(list(d))))

        t6 = f"( {d[0]} {c[0]} {d[1]} ) {c[1]} {d[2]} {c[2]} {d[3]}"

        if test_eval(t6):
            result.append(tuple(sorted(list(d))))

        t7 = f"{d[0]} {c[0]} {d[1]} {c[1]} ( {d[2]} {c[2]} {d[3]} )"

        if test_eval(t7):
            result.append(tuple(sorted(list(d))))


print(len(result))
print(len(set(result)))