题解 | #24点运算 暴力遍历 跳出双层循环

24点运算

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

# 算式的运算顺序从左至右,不包含括号,
# 左边的运算优先,不用括号表示优先级

while 1:
    try:
        s=input().split()
        #print(s)
        r=['','A','2','3','4','5','6','7','8','9','10','J','Q','K']
        sym=['+','-','*','/']
        for i in s:
            if i=='joker' or i=='JOKER':
                print('ERROR')
                break
        else:
            # 4张牌 全排列
            s_l=[]
            for i in range(4):
                s1=s[:i]+s[i+1:]
                for j in range(3):
                    s2=s1[:j]+s1[j+1:]
                    for k in range(2):
                        s3=s2[:k]+s2[k+1:]
                        s_rank=[s[i],s1[j],s2[k],s3[0]]
                        s_l.append(s_rank)
            #print(len(s_l))
            #print(s_l)

            # 4个符号任选3个排序,可重复
            sym_l=[]
            for i in sym:
                for j in sym:
                    for k in sym:
                        sym_i=[i,j,k]
                        sym_l.append(sym_i)   
            #print(len(sym_l))
            #print(sym_l)

            # 每种 s_l 与每种 sym_l 组合成新字符串,再eval
            for i in s_l:
                for j in sym_l:
                    eval1=eval(str(r.index(i[0])))
                    eval2=eval(str(eval1)+j[0]+str(r.index(i[1])))
                    eval3=eval(str(eval2)+j[1]+str(r.index(i[2])))
                    eval4=eval(str(eval3)+j[2]+str(r.index(i[3])))
                    #print(eval4)
                    if eval4==24:
                        #print(eval4)
                        print(i[0]+j[0]+i[1]+j[1]+i[2]+j[2]+i[3])
                        break  #跳出内层循环
                else:
                    continue
                break   #跳出外层循环

            else:
                print('NONE')

    except:
        break




跳出双层循环:

for i in s1:

for j in s2:

if ....:

break

else:

continue

break

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务