题解 | #24点运算#

24点运算

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

#深度优先搜索
d = {'3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'J':11, 'Q':12, 'K':13,
     'A':1, '2':2}

def f(nums, target):
    if len(nums) == 1:
        if d[nums[0]] == target:
            res.append(nums[0])
            return True
        else:
            return False
    for i in range(len(nums)):
        a = nums[i]
        b = nums[:i] + nums[i+1:]
        if f(b, target + d[a]):
            res.append('-' + a)
            return True
        elif f(b, target - d[a]):
            res.append('+' + a)
            return True
        elif f(b, target * d[a]):
            res.append('/' + a)
            return True
        elif target % d[a] == 0 and f(b, target // d[a]):
            res.append('*' + a)
            return True
    return False

while True:
    try:
        nums = input().strip()
        if "joker" in nums or "JOKER" in nums:
            print("ERROR")
        else:
            nums = nums.split()
            res = []
            if f(nums, 24):
                print(''.join(res))
            else:
                print("NONE")
    except:
        break









#穷举
# import sys
# import itertools

# def calc_24points(data):
#     map2={'J':'11','Q':'12','K':'13','A':'1'}
#     new_data=[]
#     for d in data:
#         if d in map2:
#             new_data.append(map2[d])
#         else:
#             new_data.append(d)

#     map1={'0':'+','1':'-','2':'*','3':'/'}   
#     for o in (''.join(x) for x in itertools.product(map(str,range(4)), repeat=3)):
#         for i in itertools.permutations(range(4),4):
#             temp1='(('+new_data[i[0]]+map1[o[0]]+new_data[i[1]]+')'+map1[o[1]]+new_data[i[2]]+')'+map1[o[2]]+new_data[i[3]]
#             temp2=data[i[0]]+map1[o[0]]+data[i[1]]+map1[o[1]]+data[i[2]]+map1[o[2]]+data[i[3]]
#             if ('joker' in temp1) or ('JOKER' in temp1):
#                 print('ERROR')
#                 return
#             elif eval(temp1)==24:
#                     print(temp2)
#                     return                
#     print('NONE')

# for line in sys.stdin:
#     data = list(map(str, line.strip().split()))
#     calc_24points(data)




















# import sys
# while True:
#     try:
#         ps = input().split()
#         if "joker" in ps or "JOKER" in ps:
#             print("ERROR")
#         else:
#             for i in range(len(ps)):
#                 if ps[i] == 'J':
#                     ps[i] = 11
#                 elif ps[i] == 'Q':
#                     ps[i] = 12
#                 elif ps[i] == 'K':
#                     ps[i] = 13
#                 elif ps[i] == 'A':
#                     ps[i] = 1
#             ps = list(map(int, ps))
#     #         print(ps)
#             print("NONE")

#     except:
# #         print(sys.exc_info())
#         break


















全部评论

相关推荐

无情咸鱼王的秋招日记之薛定谔的Offer:好拒信,偷了,希望有机会用到
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务