Python算24点

题意

给到扑克牌中的四张卡片,算24点。卡片A的值为1,J为11,Q为12,K为13,joker和JOKER出现时输出ERROR。如果有解,输出解的表达式,如果无解,输出ERROR。

import sys
from itertools import permutations
from itertools import combinations

获取输入

# input
s = sys.stdin.readline().strip('\n')
cards = s.split(' ')

将A,J,Q,K转为数字

# transform card name string to nums
error = False
nums = []
for c in cards:
    if c == 'JOKER' or c == 'joker':
        error = True
    elif c == 'A':
        nums.append(1)
    elif c == 'J':
        nums.append(11)
    elif c == 'Q':
        nums.append(12)
    elif c == 'K':
        nums.append(13)
    elif c.isdigit():
        nums.append(int(c))

使用permutations获取数字可能的排列

p_nums = [list(x) for x in permutations(nums)]

列出符号可能的排列

# list all possible set of choice of operators and nums
operators = ['+', '-', '*', '/']
p_op = []
t = ""
for i in range(4):
    for j in range(4):
        for k in range(4):
            t = str(operators[i]) + str(operators[j]) + str(operators[k])
            p_op.append(t)

验证符号和数字的组合是否能算出24点

#print(p_nums)
#print(p_op)
found = False
for ns in p_nums:
    if found: 
        break
    for ops in p_op:
        if found: 
            break
        left = eval(str(ns[0]) + ops[0] + str(ns[1]))
        if left != int(left) or left > 24:
            continue
        mid = eval(str(left) + ops[1] + str(ns[2]))
        if mid != int(mid) or mid > 24:
            continue
        right = eval(str(mid) + ops[2] + str(ns[3]))
        if right != int(right) or right > 24:
            continue

        s = str(ns[0]) + ops[0] + str(ns[1]) + ops[1] + str(ns[2]) + ops[2] + str(ns[3])
        
        t = []
        if eval(s) == 24:
            for i in range(4):
                if ns[i] == 'A':
                    t.append(1)
                elif ns[i] == 'J':
                    t.append(11)
                elif ns[i] == 'Q':
                    t.append(12)
                elif ns[i] == 'K':
                    t.append(13)
                else:
                    t.append(str(ns[i]))
            found = True
            s = str(t[0]) + ops[0] + str(t[1]) + ops[1] + str(t[2]) + ops[2] + str(t[3])
            print(s)
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值