递归 | HJ89 24点运算

from itertools import permutations
reflect = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, 
            '9':9, '10':10, 'J':11, 'Q':12, 'K':13, 'A':1}
record = []
def func(group, cur, sig):
    if cur == 3: 
        res = reflect[group[0]]  # 计算结果先把第一个操作数放入
        exp = f'{res}'  # 计算表达式同上
        for j in range(3):  # 判断后三个操作数和计算符号
            new_num = reflect[group[j+1]]
            new_sig = sig[j]
            exp += new_sig + str(new_num)
            res = eval(f'{res}{new_sig}{new_num}')  # eval函数计算字符串的int计算结果
        if res == 24:
            exp = exp.replace('11', 'J')  # 替换11等为J、Q、K、A
            exp = exp.replace('12', 'Q')
            exp = exp.replace('13', 'K')
            exp = exp.replace('1', 'A')
            record.append(exp)
        return
    func(group, cur+1, sig+['+'])  # 遍历递归+-*/
    func(group, cur+1, sig+['-'])
    func(group, cur+1, sig+['*'])
    func(group, cur+1, sig+['/'])    

while True:
    try:
        cards = input().split(' ')
        if 'joker' in cards or 'JOKER' in cards:
            print('ERROR')
        elif len(set(cards)) == 1:
            if '6' in cards:
                print('+'.join(cards))
            elif 'Q' in cards:
                print('Q+Q+Q-Q')
            elif '4' in cards:
                print('4*4+4+4')
            else:
                print('NONE')
        else:
            p = list(permutations(cards, 4))
            for i in p:
                func(i, 0, [])
            if record:
                print(record[0])
            else:
                print('NONE')
    except:
        break

用时:1.5h

#递归#
华为笔试刷题 文章被收录于专栏

高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107

全部评论

相关推荐

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