题解 | #24点运算#

24点运算

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

'''思路:
1. 获取四张数字牌的全排列
2. 对每一种全排列计算遍历所有可能的表达式
Tip:可以根据24在所有表达式遍历结果list中的index判断每一步都做了什么运算,从而不用在计算中保留计算方式
'''

l = 4
visited = [False]*l
s = [0]*l
allS = []
flag = 0
# dfs全排列
def allSort(pos): # i:元素为int的list
    if pos == l:
        allS.append(s.copy())
        return 
    else:
        for i in range(l):
            if not visited[i]:
                visited[i] = True
                s[pos] = li[i] # !不pop,只修改
                allSort(pos+1)
                visited[i] = False

# 处理输入
inp = input().split()
d = {
    'J': 11,
    'Q': 12,
    'K': 13,
    "A": 1,
}
d_ = {
    11: 'J',
    12: 'Q',
    13: 'K',
    1: 'A'
}
if 'joker' in inp:
    print('ERROR')
    exit()

for i in range(4):
    if inp[i] in d:
        inp[i] = d[inp[i]]
li = list(map(int, inp))
allSort(0)

def ope(a, b):
    # print(a,b)
    tmp = []
    tmp.append(a+b)
    tmp.append(a-b)
    tmp.append(a*b)
    tmp.append(a//b)
    return tmp

 # 根据24的下标求表达式,ope_n表示第n次运算
def getExp(ind, nums):
    ope3 = ind%4
    ope2 = ind//4%4
    ope1 = ind//16
    opes = ['+', '-', '*', '/']
    for i in range(4):
        if nums[i] in d_:
            nums[i] = d_[nums[i]]
    return str(nums[0])+opes[ope1]+str(nums[1])+opes[ope2]+str(nums[2])+opes[ope3]+str(nums[3])


for nums in allS:
    l1 = ope(nums[0], nums[1])
    l2 = []
    for i in l1:
        l2.extend(ope(i, nums[2]))
    l3 = []
    for i in l2:
        l3.extend(ope(i, nums[3]))
    try:
        ind = l3.index(24)
        print(getExp(ind, nums))
        flag = 1
        break
    except:
        continue

if not flag:
    print('NONE')

全部评论

相关推荐

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