老实运算,用了全排列以穷尽可能

import itertools as it
while 1:
    try:
        a,b,c,d = [int(x) for x in input().split(" ")]
        flag = False
        ls = [a,b,c,d]
        temp = list(it.permutations(ls)) #全排列,得到元组构成的列表
        #print(list(it.permutations(ls)))
        for i in temp:
            a,b,c,d = i[0],i[1],i[2],i[3]
            #print(a,b,c,d)
            first = [] #a和b运算
            second = [] #利用上面运算的结果再一次运算
            third = []  #利用上面运算的结果再一次运算
            first.append(a+b)
            first.append(a-b)
            first.append(a*b)
            first.append(a/b)

            #print(first)

            for i in first:
                second.append(i+c)
                second.append(i-c)
                second.append(i*c)
                second.append(i/c)

            #print(second)

            for k in second:
                third.append(float(k+d))
                third.append(float(k-d))
                third.append(float(k*d))
                third.append(float(k/d))
            #print(third)

            if float(24) in third:#要用浮点双精度,否则可能报错
                flag = True
        if flag == True:
            print("true")
        else:
            print('false')
    except:
        break

第二题 [链接(https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d?tpId=37&tags=&title=&difficulty=0&judgeStatus=0&rp=1]) 这个题跟第一题很像几乎一样,但要输出算式,所以不能直接一级一级算,要先构成最后的算式才开始算

from itertools import permutations
data=[str(i) for i in range(2,11)]+['A','J','Q','K']#该变量没用
a=list(map(str,input().split(' ')))
if 'joker' in a or 'JOKER' in a:
    print('ERROR')
else:
    a=' '.join(a)
    for j in a:
        if j=='A':
            a=a.replace('A','1')
        elif j=='J':
            a=a.replace('J','11')
        elif j=='Q':
            a=a.replace('Q','12')
        elif j=='K':
            a=a.replace('K','13')
    list1=['+','-','*','/']
    a=list(map(str,a.split(' ')))
    aaa=list(permutations(a))
    list2=[]
    for aa in aaa:
      for x1 in list1:
        for x2 in list1:
            for x3 in list1:
                aa=list(aa)
                y='(('+aa[0]+x1+aa[1]+')'+x2+aa[2]+')'+x3+aa[3]
                y1=eval(y)
                y2=aa[0]+x1+aa[1]+x2+aa[2]+x3+aa[3]
                if y1==24 or y1==24.0:
                    list2.append(y2)

    if len(list2)!=0:  
        if '1' in list2[0]:
           list2[0]=list2[0].replace('1','A')
           if 'AA' in list2[0]:
               list2[0]=list2[0].replace('AA','J')
           if 'A2' in list2[0]:
               list2[0]=list2[0].replace('A2','Q')
           if 'A3' in list2[0]:
               list2[0]=list2[0].replace('A3','K')
        print(list2[0])
    else:
        print('NONE')