题解 | #24点运算#

24点运算

https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d

from re import T
import sys

porker = {'J':'11','Q':'12','K':'13','A':'1'}
def check(numlist, res, sym):
    if len(numlist)==0:
        if res == 24:
            return True, sym
        else:
            return False, sym
    else:
        allflag = False
        for i in range(len(numlist)):
            left = numlist[:i]+numlist[i+1:]
            v = numlist[i]
            if res==0:
                allflag, sym = check(left, int(v), v)
            else:
                flagadd, addsym = check(left, res+int(v), sym+'+'+v)
                flagsub, subsym = check(left, res-int(v), sym+'-'+v)
                flagmut, mutsym = check(left, res*int(v), sym+'*'+v)
                flagdiv, divsym = check(left, res/int(v), sym+'/'+v)
                flag = flagadd or flagsub or flagmut or flagdiv
                allflag = allflag or flag
                if flagadd:
                    sym = addsym
                if flagsub:
                    sym = subsym
                if flagmut:
                    sym = mutsym
                if flagdiv:
                    sym = divsym
            if allflag:
                break
        return allflag, sym

for line in sys.stdin:
    a = line.split()
    error = False
    for j in range(len(a)):
        this = a[j]
        if not this.isdigit():
            if this in porker.keys():
                a[j] = porker[this]
            else:
                error = True
                break
    if error:
        print('ERROR')
    else:
        do, sym = check(a,0,'')
        if do:
            sym = sym.replace('11','J')
            sym = sym.replace('12','Q')
            sym = sym.replace('13','K')
            sym = sym.replace('1','A')
            print(sym)
        else:
            print('NONE')

全部评论

相关推荐

11-14 16:13
已编辑
重庆科技大学 测试工程师
Amazarashi66:不进帖子我都知道🐮❤️网什么含金量
点赞 评论 收藏
分享
死在JAVA的王小美:哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈,我也是,让我免了一轮,但是硬气拒绝了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务