编辑代码

# coding:utf-8
#JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
#print("Hello world!   -  python.jsrun.net .")
import itertools
import math

def format_number(num):
    """将数字格式化为整数或浮点数字符串"""
    if num == int(num):
        return str(int(num))
    else:
        # 移除末尾的零和多余的小数点
        return f"{num:.10f}".rstrip('0').rstrip('.') 

def perform_op(a, op, b):
    """执行单个运算并处理除零错误"""
    try:
        if op == '+':
            return a + b
        elif op == '-':
            return a - b
        elif op == '*':
            return a * b
        elif op == '/':
            return a / b
        else:
            return None
    except ZeroDivisionError:
        return None

def compute_struct1(n1, n2, n3, n4, op1, op2, op3):
    """结构1:((a op1 b) op2 c) op3 d"""
    a, b, c, d = n1, n2, n3, n4
    step1 = perform_op(a, op1, b)
    if step1 is None:
        return None, None
    step2 = perform_op(step1, op2, c)
    if step2 is None:
        return None, None
    step3 = perform_op(step2, op3, d)
    if step3 is None:
        return None, None
    expr = f"(({format_number(a)}{op1}{format_number(b)}){op2}{format_number(c)}){op3}{format_number(d)}"
    return step3, expr

def compute_struct2(n1, n2, n3, n4, op1, op2, op3):
    """结构2:(a op1 (b op2 c)) op3 d"""
    a, b, c, d = n1, n2, n3, n4
    step1 = perform_op(b, op2, c)
    if step1 is None:
        return None, None
    step2 = perform_op(a, op1, step1)
    if step2 is None:
        return None, None
    step3 = perform_op(step2, op3, d)
    if step3 is None:
        return None, None
    expr = f"({format_number(a)}{op1}({format_number(b)}{op2}{format_number(c)})){op3}{format_number(d)}"
    return step3, expr

def compute_struct3(n1, n2, n3, n4, op1, op2, op3):
    """结构3:a op1 ((b op2 c) op3 d)"""
    a, b, c, d = n1, n2, n3, n4
    step1 = perform_op(b, op2, c)
    if step1 is None:
        return None, None
    step2 = perform_op(step1, op3, d)
    if step2 is None:
        return None, None
    step3 = perform_op(a, op1, step2)
    if step3 is None:
        return None, None
    expr = f"{format_number(a)}{op1}(({format_number(b)}{op2}{format_number(c)}){op3}{format_number(d)})"
    return step3, expr

def compute_struct4(n1, n2, n3, n4, op1, op2, op3):
    """结构4:a op1 (b op2 (c op3 d))"""
    a, b, c, d = n1, n2, n3, n4
    step1 = perform_op(c, op3, d)
    if step1 is None:
        return None, None
    step2 = perform_op(b, op2, step1)
    if step2 is None:
        return None, None
    step3 = perform_op(a, op1, step2)
    if step3 is None:
        return None, None
    expr = f"{format_number(a)}{op1}({format_number(b)}{op2}({format_number(c)}{op3}{format_number(d)}))"
    return step3, expr

def compute_struct5(n1, n2, n3, n4, op1, op2, op3):
    """结构5:(a op1 b) op2 (c op3 d)"""
    a, b, c, d = n1, n2, n3, n4
    step1 = perform_op(a, op1, b)
    if step1 is None:
        return None, None
    step2 = perform_op(c, op3, d)
    if step2 is None:
        return None, None
    step3 = perform_op(step1, op2, step2)
    if step3 is None:
        return None, None
    expr = f"({format_number(a)}{op1}{format_number(b)}){op2}({format_number(c)}{op3}{format_number(d)})"
    return step3, expr

# 所有结构函数的列表
structures = [compute_struct1, compute_struct2, compute_struct3, compute_struct4, compute_struct5]

def solve_24(nums):
    """解24点游戏,返回所有可能的解法"""
    solutions = set()
    # 遍历所有数字排列
    for perm in itertools.permutations(nums):
        n1, n2, n3, n4 = perm
        # 遍历所有运算符组合
        for ops in itertools.product('+-*/', repeat=3):
            op1, op2, op3 = ops
            # 遍历所有结构
            for struct in structures:
                result, expr = struct(n1, n2, n3, n4, op1, op2, op3)
                if result is not None and math.isclose(result, 24, rel_tol=1e-9, abs_tol=1e-9):
                    solutions.add(expr)
    return solutions

if __name__ == "__main__":
    # 用户输入处理
    nums = list(map(float, input("请输入四个数字(用空格分隔): ").split()))
    if len(nums) != 4:
        print("请输入四个数字!")
    else:
        solutions = solve_24(nums)
        if solutions:
            print("找到的解法:")
            for sol in sorted(solutions):
                print(f"{sol} = 24")
        else:
            print("无解")