高赞题解的详细注释版 | #24点运算#

24点运算

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

# 暴力枚举
from itertools import permutations
 
card = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
order = range(1,14)
card_order = dict(zip(card,order))
opts = ["+", "-", "*", "/"]
 
def cal(a1,a2,opt):
    if opt == 0: return a1+a2
    elif opt == 1: return a1-a2
    elif opt == 2: return a1*a2
    elif opt == 3: return a1/a2
 
def cal24(cards):
    # 如果有王
    if "joker" in cards or "JOKER" in cards:
        print("ERROR")
        return
    num_orders = permutations(cards, 4) # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # 遍历4个数字的组合
    for nums in num_orders:
        # 遍历运算符,第1个数与第2个数的计算
        for i in range(4):
            a = cal(card_order[nums[0]], card_order[nums[1]], i)
            # 遍历运算符,前面运算结果与第3个数的计算
            for j in range(4):
                b = cal(a, card_order[nums[2]], j)
                # 遍历运算符,前面运算结果与第4个数的计算
                for k in range(4):
                    c = cal(b, card_order[nums[3]], k)
                    # 如果最终结果为24,则输出
                    if c == 24:
                        print("%s%s%s%s%s%s%s"%(nums[0],opts[i],nums[1],opts[j],nums[2],opts[k],nums[3]))
                        return
    print("NONE")
    return
 
cards = input().split()
cal24(cards)

全部评论

相关推荐

勤奋努力的椰子这就开摆:美团骑手在美团工作没毛病
投递美团等公司10个岗位
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务