首页 > 试题广场 >

24点运算

[编程题]24点运算
  • 热度指数:87714 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

计算24点是一种扑克牌益智游戏,随机抽出4张扑克牌,通过加(+),减(-),乘(*), (/)四种运算法则计算得到整数24,本问题中,扑克牌通过如下字符或者字符串表示,其中,小写joker表示小王,大写JOKER表示大王:

3 4 5 6 7 8 9 10 J Q K A 2 joker JOKER

本程序要求实现:输入4张牌,输出一个算式,算式的结果为24点。

详细说明:

1.运算只考虑加减乘除运算,没有阶乘等特殊运算符号,没有括号,友情提醒,整数除法要当心,是属于整除,比如2/3=0,3/2=1
2.牌面2~10对应的权值为2~10, JQKA权值分别为为1112131
3.输入4张牌为字符串形式,以一个空格隔开,首尾无空格;如果输入的4张牌中包含大小王,则输出字符串“ERROR”,表示无法运算;
4.输出的算式格式为4张牌通过+-*/四个运算符相连,中间无空格4张牌出现顺序任意,只要结果正确;
5.输出算式的运算顺序从左至右,不包含括号,如1+2+3*4的结果为24,2 A 9 A不能变为(2+1)*(9-1)=24
6.如果存在多种算式都能计算得出24,只需输出一种即可,如果无法得出24,则输出“NONE”表示无解。
7.因为都是扑克牌,不存在单个牌为0的情况,且没有括号运算,除数(即分母)的数字不可能为0

数据范围:一行由4张牌组成的字符串

输入描述:

输入4张牌为字符串形式,以一个空格隔开,首尾无空格;



输出描述:
输出怎么运算得到24,如果无法得出24,则输出“NONE”表示无解,如果输入的4张牌中包含大小王,则输出字符串“ERROR”,表示无法运算;
示例1

输入

A A A A

输出

NONE

说明

不能实现           
示例2

输入

4 2 K A

输出

K-A*4/2

说明

 A+K*2-4也是一种答案,输出任意一种即可           
示例3

输入

B 5 joker 4

输出

ERROR

说明

 存在joker,输出ERROR          
示例4

输入

K Q 6 K

输出

NONE

说明

按一般的计算规则来看,K+K-(Q/6)=24 或 K-((Q/6)-K)=24,但是因为这个题目的运算不许有括号,所以去掉括号后变为 K+K-Q/6=26-Q/6=14/6=2 或 K-Q/6-K=1/6-K=0-K=-13,其它情况也不能运算出24点,故不存在,输出NONE   
import itertools#一开始看蒙了。。这道题是允许特殊运算(带括号)但是出来的output不显示括号
def calculation (num):#直接复制之前那道的功能,处理num数据就好了
    mark = ['+','-','*','/'] #全部加减乘除
    for allcomb in itertools.permutations(num):#列出全部可能
        a,b,c,d = allcomb 
        for i in mark:
            for j in mark:
                for k in mark:#全部可能性 与全部加减乘除
                    value1 = a + i + b
                   # value2 = a + i + b + j + c   # 不允许括号情况下常规运算
                   # value3 = a + i + b + j + c + k + d
                    value2 = str(eval(value1))+ j + c
                    value3 = str(eval(value2))+ k + d#允许括号情况下特殊运算
                    value4 = a + i + b + j + c + k + d#这道题用于记录无括号的string
                    fina3 = eval(value3)
                    if fina3 == 24:
                        return value4#返回不带括号的结果
    else:
        return 'NONE'
while True:
    try:
        str1 = input()#读取数据
        str1=str1.replace('A', '1')#处理替换为数字
        str1=str1.replace('J', '11')
        str1=str1.replace('Q', '12')
        str1=str1.replace('K', '13')
        if 'joker' in str1.lower():#当出现joker时打印ERROR
            print('ERROR')
        else:
            str1=str1.split()#以空格区分
            returned = calculation(str1)#带入上面功能读取返回值
            if returned !='NONE':#返回值不是NONE时
                returned = returned.replace('11', 'J')#替换回字母,注意先后顺序先处理二位数再处理A
                returned = returned.replace('12', 'Q')
                returned = returned.replace('13', 'K')
                returned = returned.replace('1', 'A')
                print(returned)#打印转换后的结果
            else:
                print(returned)#打印NONE
    except:
        break

编辑于 2021-07-01 15:25:17 回复(0)
由于本题限制了从左到右的计算顺序,导致有些可以通过四则运算计算出24点的情况,在当前的规则下会输出NONE,如"2 A 9 A"。
此外,题干中并未说明开头的数是否可用负数(可能【四个牌用运算符相连】的说法隐含了不能首位负数的条件吧)。从测试用例来看,是不考虑首位负数的,我加入首位负数输出的答案被判定为错误,而取消首位负数后就通过了。如果在第一个数字之前还有插入"-"运算符的可能,那么如"5 5 5 A"这样的情况就有-A/5+5*5这样的解法。
因此,在本题限制的规则下,其实有些输出NONE的情况,在不强制限定计算顺序时是可以通过四则运算算出24点的。
import sys
from itertools import permutations 

def CalValue(num1, op, num2):
    try:
        return eval(num1+op+num2)
    except:
        return None

def Cal24(cards):
    cardNum = {'A':'1', '1':'1', '2':'2', '3':'3', '4':'4', '5':'5', '6':'6', '7':'7', '8':'8', '9':'9', '10':'10', 'J':'11', 'Q':'12', 'K':'13'}
    operator = r'+-*/'
    for comb in permutations(cards):
        for op1 in operator:
            for op2 in operator:
                for op3 in operator:
                    '''
                    for op0 in ['', '-']:  #考虑首位负数的情况
                        value1stage = CalValue(op0+cardNum[comb[0]], op1, cardNum[comb[1]])
                        if value1stage is None: continue
                        value2stage = CalValue(str(value1stage), op2, cardNum[comb[2]])
                        if value2stage is None: continue
                        value3stage = CalValue(str(value2stage), op3, cardNum[comb[3]])
                        if value3stage is None: continue
                        if value3stage==24:
                            result = op0+comb[0]+op1+comb[1]+op2+comb[2]+op3+comb[3] 
                            return result
                    '''
                    value1stage = CalValue(cardNum[comb[0]], op1, cardNum[comb[1]])
                    if value1stage is None: continue
                    value2stage = CalValue(str(value1stage), op2, cardNum[comb[2]])
                    if value2stage is None: continue
                    value3stage = CalValue(str(value2stage), op3, cardNum[comb[3]])
                    if value3stage is None: continue
                    if value3stage==24:
                        result = comb[0]+op1+comb[1]+op2+comb[2]+op3+comb[3] 
                        return result
    return 'NONE'

for line in sys.stdin:
    if 'joker' in line or 'JOKER' in line:
        print('ERROR')
    else:
        cards = line.rstrip('\n').replace('1', 'A').split(' ')
        print(Cal24(cards))

编辑于 2021-03-10 13:00:24 回复(0)
为什么我在自己pycharm编辑器中可以正常运行,牛客网提交代码后就报错?究竟是谁的问题?
x_list = input().split()
EOFError: EOF when reading a line

发表于 2021-03-09 10:52:06 回复(0)

25ms 3192KB
用递归做,用24往下加减乘除,记录反向操作


import copy


def recurrence(card, n, s):
    if n < 1:
        return
    if len(card) == 1:
        if card[0] == n:
            res.append(str(int(n)) + s)
        else:
            return
    for i in range(len(card)):
        temp = copy.deepcopy(card)
        a = temp.pop(i)
        recurrence(temp, n + a, '-' + str(a) + s)
        recurrence(temp, n - a, '+' + str(a) + s)
        recurrence(temp, n * a, '/' + str(a) + s)
        recurrence(temp, n / a, '*' + str(a) + s)
    
    
while True:
    try:
        res = []
        dic = {'K': 13,
              'Q': 12,
              'J': 11,
              'A': 1}
        cards = input().split()
        if 'joker' in cards&nbs***bsp;'JORKER' in cards:
            print('ERROR')
        else:
            cards = [int(i) if i.isdigit() else dic[i] for i in cards]
            recurrence(cards, 24, '')
            if not res:
                print('NONE')
            else:
                res[0] = res[0].replace('11', 'J').replace('12', 'Q').replace('13', 'K').replace('1', 'A')
                print(res[0])
    except:
        break


编辑于 2021-02-20 22:33:42 回复(0)
看不了用例,也不知道哪里出问题了。。
from itertools import permutations
while True:
    try:
        dict = {'J':'11','Q':'12','K':'13','A':'1'}
        operator = ['+','-','*','/']
        s = input().split(' ')
        l = []
        mark = 1
        for i in s:
            if i.isnumeric():
                l.append(i)
            else:
                try:
                    l.append(dict[i])
                except:
                    print('ERROR')
                    mark = 0
                    break
        if not mark:
            break
        for subs in permutations(l):
            for i in operator:
                for j in operator:
                    for k in operator:
                        if mark:
                            expression = list(subs).copy()
                            expression.insert(1,i)
                            expression.insert(3,j)
                            expression.insert(5,k)
                            start = eval(''.join(expression[0:3]))
                            for m in range(2):
                                start = eval(str(start)+expression[2*m+3]+expression[2*m+4])
                            if start==24:
                                print(''.join(expression))
                                mark = 0
        if mark:
            print('NONE')
    except:
        break

发表于 2021-02-15 11:00:23 回复(0)
import itertools as it
import sys

card_dict = {'A':'1','2':'2','3':'3','4':'4','5':'5','6':'6','7':'7','8':'8','9':'9','10':'10','J':'11','Q':'12','K':'13'}
card_dict1 = dict(zip(card_dict.values(),card_dict.keys()))
opts = ['+','-','*','/']
def calculate(input_cards):
    cards = [card_dict.get(x) for x in input_cards]
    for opt in it.product(opts,repeat=3):
        for nums in it.permutations(cards, 4):
            temp = "(({n1}{op1}{n2}){op2}{n3}){op3}{n4}".format(n1=nums[0],n2=nums[1],n3=nums[2],n4=nums[3],op1=opt[0],op2=opt[1],op3=opt[2])
            summ = 0
            try:
                summ = eval(temp)
            except:
                pass
            if summ == 24:
                expr = '{}{}{}{}{}{}{}'.format(card_dict1.get(nums[0]),opt[0],card_dict1.get(nums[1]),opt[1],card_dict1.get(nums[2]),opt[2],card_dict1.get(nums[3]))
                return expr
    return 'NONE'

lines = sys.stdin.readlines()
for cards in lines:
    if not cards:
        continue
    if 'joker' in cards or 'JOKER' in cards:
        print('ERROR')
    else:
        res = calculate(cards)
        print(res)

发表于 2021-01-22 14:31:44 回复(0)
# 思路:对所有数字全排列,计算每种排列能否凑成24(题目默认按照先后顺序计算,即((a+b)+c))+d模式。
# 如果joker 或 JOKER 在输入序列中,返回ERROR
# 当有一个满足的解时,返回;遍历完所有排列,如果没有满足的解,返回NONE
from itertools import permutations

def game24(poker_list):
    dic = {'A': '1', '2': '2', '3': '3', '4': '4', '5': '5',
           '6': '6', '7': '7', '8': '8', '9': '9', '10': '10',
           'J': '11', 'Q': '12', 'K': '13'}
    ops = ['+', '-', '*', '/']
    for nums in permutations(poker_list):
        a, b, c, d = nums
        for i in ops:
            for j in ops:
                for k in ops:
                    fir = str(eval(dic[a] + i + dic[b]))
                    sec = str(eval(fir + j + dic[c]))
                    if eval(sec + k + dic[d]) == 24:
                        return ''.join([a,i,b,j,c,k,d])
    return "NONE"


while True:
    try:
        poker_list = input().strip().split(' ')
        if 'joker' in poker_list or 'JOKER' in poker_list:
            print('ERROR')
        else:
            print(game24(poker_list))
    except:
        break

编辑于 2021-01-04 11:53:53 回复(0)
import sys
from itertools import permutations, product


cards = "0 A 2 3 4 5 6 7 8 9 10 J Q K".split()
operators = ["+", "-", "*", "/"]


def helper(nums):
    for c in permutations(nums):
        for o in product(operators, repeat=3):
            e = "(({}{}{}){}{}){}{}".format(c[0], o[0], c[1], o[1], c[2], o[2], c[3])
            if eval(e) == 24:
                return cards[c[0]]+o[0]+cards[c[1]]+o[1]+cards[c[2]]+o[2]+cards[c[3]]
    return "NONE"


for s in sys.stdin:
    s = s.strip()
    if "joker" in s.lower():
        print("ERROR")
        continue
    nums = [cards.index(i) for i in s.split()]
    print(helper(nums))

发表于 2020-12-18 19:00:02 回复(0)
求大神帮看看到底是什么还没有考虑到orz,通过率80%,枯了
def num_to_C(s):
    s = s.replace("11", "J")
    s = s.replace("12", "Q")
    s = s.replace("13", "K")
    s = s.replace("1", "A")
    return s

def C_to_num(s):
    s = s.replace("J", "11")
    s = s.replace("Q", "12")
    s = s.replace("K", "13")
    s = s.replace("A", "1")
    return s

while True:
    try:
        s = input()
        s = C_to_num(s)
        s = s.split(" ")
        #判断是否是正常输入
        if_continue = True
        if not len(s)==4: 
            print("ERROR")
            if_continue = False
        for num in s:
            if not num.isdigit(): 
                print("ERROR")
                if_continue = False
            elif not int(num) in range(1,14):
                print("ERROR")
                if_continue=False
        if if_continue:
            if ("JOKER" in s) or ("joker" in s):
                print("ERROR")
            else:
                
                o = ["+", "-", "*", "/"]
                operant_zuhe = []
                operant = ["","","",""]
                operator_zuhe = []
                operator = []
                #列出四个数字的所有排列顺序,放在operant_zuhe里
                for c1 in s:
                    operant[0]=c1
                    for c2 in s:
                        if not c2==c1:
                            operant[1]=c2
                            for c3 in s:
                                if not (c3==c1 or c3==c2):
                                    operant[2]=c3
                                    for c4 in s:
                                        if not (c4==c1 or c4==c2 or c4==c3):
                                            operant[3]=c4
                                            operant_copy = operant[:]
                                            #print(operant)
                                            operant_zuhe.append(operant_copy)
                equa2 = []
                equa3 = []
                #在数字的组合中间加上运算符并计算
                for operant in operant_zuhe:
                    equa = []
                    equa2 = []
                    #print(operant)
                    for opr in o:
                        equa.append([operant[0]+opr+operant[1], eval(operant[0]+opr+operant[1])])         
                    for e in equa:
                        for opr in o:
                            equa2.append([e[0]+opr+operant[2], eval(str(e[1])+opr+operant[2])])
                    for e in equa2:
                        for opr in o:
                            equa3.append([e[0]+opr+operant[3], eval(str(e[1])+opr+operant[3])])
                #print(len(equa3))
                succ = False
                for e in equa3:
                    #val = eval(e)
                    if e[1]==24:
                        succ = True
                        #print("1")
                        print(num_to_C(e[0]))
                        #print(remove_pa('(((A+2)+3)*4)'))
                        break
                if succ==False:
                    print("NONE")
    except:
        break

编辑于 2020-12-02 19:05:53 回复(0)
穷举,python,全排列,cv来的

# 思路:对所有数字全排列,计算每种排列能否凑成24(题目默认按照先后顺序计算,即((a+b)+c))+d模式。
# 如果joker 或 JOKER 在输入序列中,返回ERROR
# 当有一个满足的解时,返回;遍历完所有排列,如果没有满足的解,返回NONE
from itertools import permutations

while True:
    try:
        def check(exp):  # 为了排除中间/0的情况,并且若等式值为24,返回True
            try:
                return int(eval(exp) == 24)
            except:
                return False
            
        def game24(pokers):
            dic = {'A': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9', '10': '10',
                   'J': '11', 'Q': '12', 'K': '13'}
            ops = r'+-*/'
            exp = '((%s %s %s) %s %s )%s %s'  ## 这道题默认括号是这么加的
            for a in permutations(pokers):  ## nums 的全排列
                for op1 in ops:
                    for op2 in ops:
                        for op3 in ops:
                            if check(exp % (dic[a[0]], op1, dic[a[1]], op2, dic[a[2]], op3, dic[a[3]])):
                                result = a[0] + op1 + a[1] + op2 + a[2] + op3 + a[3]  ## 这题只需要求出一个满足要求的等式即可
                                return result
            return 'NONE'
        pokers = input().split(' ')
        if 'joker' in pokers or 'JOKER' in pokers:
            print('ERROR')
        else:
            print(game24(pokers))
    except:
        break


编辑于 2020-11-22 00:28:14 回复(0)
from itertools import permutations
from itertools import product


class Solution:
    def find_match_case(self, rcards):
        kinds = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
        opert = ['+', '-', '*', '/']  # operator

        trans = {val: i + 1 for i, val in enumerate(kinds)}  # 得到牌面和实际值的转换字典
        cards = [trans[card] for card in rcards]  # 牌面实际值

        templ = "((%s %s %s) %s %s) %s %s"  # 用于eval计算的模板
        answe = "%s%s%s%s%s%s%s"  # 用于返回正确答案的模板

        for n1, n2, n3, n4 in permutations(range(4), 4):  # 四个数字全排列
            for op1, op2, op3 in product(range(4), repeat=3):  # 三个操作符笛卡尔积
                combine = templ % (cards[n1], opert[op1], cards[n2], opert[op2], cards[n3], opert[op3], cards[n4])

                if abs(eval(combine) - 24) < 0.00001:  # 保险起见,还是用了一个近似值做判断
                    return answe % (rcards[n1], opert[op1], rcards[n2], opert[op2], rcards[n3], opert[op3], rcards[n4])

        return "NONE"


if __name__ == '__main__':
    solution = Solution()
    data = input().strip().split()

    for c in data:
        if c in {"joker", "JOKER"}:
            print("ERROR")
            break
    else: print(solution.find_match_case(data))

发表于 2020-09-08 00:32:36 回复(0)
没招了,应该是测试用例没包含全部解,只通过60%,没有展示测试用例。记录下思路

基本思路就是穷举 
先 运算符 [+,-,*,/] 用笛卡尔积算出所有可能性    permutations 算出所有数字排列 
chain.from_iterable 交叉数字、运算符 组成列表,
1:链接成字符串 eval 计算结果判断,如无解
2:尝试添加括号计算 
添加括号穷举思路:
列表长度固定8.随机添加两个括号,长度为12。12取4求排列
因:左(下标大于3 或 右)下标小于5的排列没有意义,过滤
3:eval 链接字符串计算带括号解,如无解,则输出none


import itertools
def jisuan(j):
    s1 = ""
    for i in j:
        if i == "A":
            s1 += "1"
        elif i == "J":
            s1 += "11"
        elif i == "Q":
            s1 += "12"
        elif i == "K":
            s1 += "13"
        else:
            s1 += i
    try:
        if eval(s1) == 24:
            print("".join(j).strip().replace("(", "").replace(")", ""))
            return True
    except Exception:
        return False


def add(j):

    # 随机加两个()列表长度固定8 +4 求排列
    per = itertools.permutations(range(12), 4)
    per = filter(lambda x: x[0] < 3 and x[3]>5, [i for i in per])
    for i in per:
        ll = j.copy()
        ll.insert(i[0], "(")
        ll.insert(i[1] + 1, ")")
        ll.insert(i[2] + 2, "(")
        ll.insert(i[3] + 3, ")")

        if jisuan(ll):
            return True


def ershisi():
    s = input().upper()
    l1 = s.split(" ")
    if s.count("JOKER") > 0:
        print("ERROR")
        return
    
    for i in l1:
        if not i.isdigit() and i not in ["A", "J", "Q", "K"]:
            #print("NONE")
            return
    fu_hao = ["+", "-", "*", "/"]
    # 穷举符号
    qiongju = itertools.product(fu_hao, fu_hao, fu_hao)
    # j = list(itertools.chain.from_iterable(zip(fu_hao,fi)))

    for item in itertools.permutations(l1, 4):
        for l2 in qiongju:
            l2 = list(l2)  # 只有三位,补足
            l2.append(" ")
            j = list(itertools.chain.from_iterable(zip(item, l2)))
            if jisuan(j):  # 正常计算
                return
            if add(j):  # 添加括号计算
                return
    print("NONE")


ershisi()


发表于 2020-08-26 14:40:17 回复(0)
from copy import deepcopy
a = {"J": 11, "Q": 12, "K": 13, "A": 1}

class points:
    def __init__(self):
        self.res = ""
        self.cal = []

    def helper(self, cards, asum, k, m, used, c):
        self.cal.append(c)
        if len(cards) == 0 and int(asum) == k:
            # print(self.cal)
            for i in range(len(used)):
                num = ""
                if used[i]==11:
                    num = "J"
                elif used[i]==12:
                    num = "Q"
                elif used[i]==13:
                    num = "K"
                elif used[i]==1:
                    num = "A"
                else:
                    num = str(used[i])
                self.res += self.cal[i] + num
            return True
        elif len(cards) == 0:
            # self.cal.pop(-1)
            return False
        else:
            for i in range(len(cards)):
                card_1 = cards.pop(i)
                card_2 = asum
                cp_cards = deepcopy(cards)
                add = card_1 + card_2
                minus1 = card_1 - card_2
                minus2 = card_2 - card_1
                used.append(card_1)
                # m=0表示上一个操作是加减
                if self.helper(cp_cards, add, k, 0, used, "+"):
                    return True
                else:
                    self.cal.pop(-1)
                if self.helper(cp_cards, minus1, k, 0, used, "-"):
                    return True
                else:
                    self.cal.pop(-1)
                if self.helper(cp_cards, minus2, k, 0, used, "-"):
                    return True
                else:
                    self.cal.pop(-1)
                if m == 1:
                    chen = card_1 * card_2
                    chu1 = card_1 / card_2
                    chu2 = card_2 / card_1
                    if self.helper(cp_cards, chen, k, 1, used, "*"):
                        return True
                    else:
                        self.cal.pop(-1)
                    if self.helper(cp_cards, chu1, k, 1, used, "/"):
                        return True
                    else:
                        self.cal.pop(-1)
                    if self.helper(cp_cards, chu2, k, 1, used, "/"):
                        return True
                    else:
                        self.cal.pop(-1)
                cards.insert(i, card_1)
                used.pop(-1)

while True:
    try:
        
        content = input().split()
        #content = ["A", "2", "3", "4"]
        if "joker" in content&nbs***bsp;"JOKER" in content:
            print("ERROR")
        else:
            cards = []
            for i in content:
                if i in a.keys():
                    cards.append(a[i])
                else:
                    cards.append(int(i))
            kk = 0
            # print("cards", cards)
            pro = points()
            for i in range(len(cards)):
                used = []
                c = ''
                asum = cards.pop(i)
                used.append(asum)
                if pro.helper(cards, asum, 24, 1, used, c):
                    kk = 1
                    print(pro.res)
                    break
                cards.insert(i, asum)
            if kk == 0:
                print("NONE")
    except:
        break
# print(kk)

为什么只能过65%,烦死了
发表于 2020-08-19 17:21:23 回复(0)
dict1 = {'A': 1, 'J': 11, 'Q': 12, 'K': 13}
opt = ['+', '-', '*', '/']
while 1:
    try:
        list = input().strip().split()
        if 'joker' in list&nbs***bsp;'JOKER' in list:
            print('ERROR')
            break
        list1 = []
        for i in list:
            if i in dict1.keys():
                list1.append(dict1[i])
            else:
                list1.append(int(i))
        res = False
        for i in range(4):
            for j in range(4):
                if j != i:
                    for k in range(4):
                        if k not in [i, j]:
                            index = [0,1,2,3]
                            index.remove(i)
                            index.remove(j)
                            index.remove(k)
                            m = index[0]
                            num1, num2, num3, num4 = list1[i], list1[j], list1[k], list1[m]
                            for op1 in opt:
                                if op1 == '+':
                                    a1 = num1 + num2
                                if op1 == '-':
                                    a1 = num1 - num2
                                if op1 == '*':
                                    a1 = num1 * num2
                                if op1 == '/':
                                    a1 = num1 / num2
                                for op2 in opt:
                                    if op2 == '+':
                                        a2 = a1 + num3
                                    if op2 == '-':
                                        a2 = a1 - num3
                                    if op2 == '*':
                                        a2 = a1 * num3
                                    if op2 == '/':
                                        a2 = a1 / num3
                                    for op3 in opt:
                                        if op3 == '+':
                                            a3 = a2 + num4
                                        if op3 == '-':
                                            a3 = a2 - num4
                                        if op3 == '*':
                                            a3 = a2 * num4
                                        if op3 == '/':
                                            a3 = a2 / num4
                                        if a3 == 24:
                                            res = True
                                            print('%s%s%s%s%s%s%s' % (list[i], op1, list[j], op2, list[k], op3, list[m]))
                                            break
        if not res:
            print("NONE")
    except:
        break

发表于 2020-08-16 21:49:17 回复(0)
import itertools
Dic1={'A':'1','J':'11','Q':'12','K':'13'}
cal={'0':'+','1':'-','2':'*','3':'/'}

while True:
    try:
        mylist=list(map(str,input().split()))
        mylist2=[]
        if ('joker' in mylist)&nbs***bsp;('JOKER' in mylist):
            print('ERROR')
        else:
            for i in mylist:
                if i in Dic1.keys:
                    mylist2.append(mylist[Dic1[i]])
                else:
                    mylist2.append(i)
            for x in (''.join(m) for m in itertools.product(map(str,range(4)),repeat=3)):
                for j in itertools.permutations(range(4),4):
                    temp1='(('+mylist2[j[0]]+cal[x[0]]+mylist2[j[1]]+')'+cal[x[1]]+mylist2[j[2]]+')'+cal[x[2]]+mylist2[j[3]]
                    temp2=mylist2[j[0]]+cal[x[0]]+mylist2[j[1]]+cal[x[1]]+mylist2[j[2]]+cal[x[2]]+mylist2[j[3]]
                    if eval(temp1)==24:
                        print(temp2)
        print('NONE')
    except:
        break
哪位大佬可以帮忙看一下,这段代码为啥只能通过50%?谢谢~
发表于 2020-08-14 21:57:06 回复(0)
class solution:
    def __init__(self, reverse_dic):
        self.res = False
        self.path = ""
        self.dic = reverse_dic
    
    def backtrack(self, index, nums, curVal, path):
        if nums == []:
            if curVal == 24:
                self.res = True
                self.path = path
            return
        if self.res:
            return
        if index == 0:
            for i in range(len(nums)):
                new_num = nums[:i] + nums[i+1:]
                self.backtrack(index + 1, new_num, nums[i], path + self.dic[nums[i]])
        else:
            for i in range(len(nums)):
                new_num = nums[:i] + nums[i+1:]
                self.backtrack(index + 1, new_num, curVal + nums[i], path + "+" + self.dic[nums[i]])
                self.backtrack(index + 1, new_num, curVal - nums[i], path + "-" + self.dic[nums[i]])
                self.backtrack(index + 1, new_num, curVal * nums[i], path + "*" + self.dic[nums[i]])
                self.backtrack(index + 1, new_num, curVal / nums[i], path + "/" + self.dic[nums[i]])

while True:
    try:
        nums = input()
        dic = {'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, 'joker':None, 'JOKER':None}
        reverse_dic = {3:'3', 4:'4', 5:'5', 6:'6', 7:'7', 8:'8', 9:'9', 10:'10', 11:'J', 12:'Q', 13:'K', 1:'A', 2:'2'}
        nums = [dic[i] for i in nums.split()]
        if None in nums:
            print('ERROR')
        else:
            c = solution(reverse_dic)
            c.backtrack(0, nums, 0, "")
            print(c.path if c.res else 'NONE')
    except:
        break

发表于 2020-07-26 16:06:28 回复(0)
import copy
import itertools

hand = input().split()

if ('joker' in hand) | ('JOKER' in hand):
    print('ERROR')
else:
    mp = {'J':'11','Q':'12','K':'13','A':'1'}
    
    for i in range(4):
        if hand[i] in mp:
            hand[i] = mp[hand[i]]
    
    hn = [float(x) for x in hand]

    def opt(sign,a,b):
        if sign == '+':
            return a+b 
        elif sign == '-':
            return a-b 
        elif sign == '*':
            return a*b
        elif sign == '/':
            return a/b

    optset = ['+','-','*','/']
    pn = list(itertools.permutations([0, 1, 2, 3]))
    po = list(itertools.combinations_with_replacement([0, 1, 2, 3], 3))

    def get24n(hno):
        for x in pn:
            for y in po:
                a,b,c,d = hno[x[0]],hno[x[1]],hno[x[2]],hno[x[3]]
                o1,o2,o3 = optset[y[0]],optset[y[1]],optset[y[2]]
                res = opt(o3,opt(o2,opt(o1, a, b),c),d)
                if res == 24.:
                    return [str(int(a)),o1,str(int(b)),o2,str(int(c)),o3,str(int(d))]
        return 'NONE'

    out = get24n(hn)
    mp = {'11':'J','12':'Q','13':'K','1':'A'}
    for i in range(len(out)):
        if out[i] in mp:
            out[i] = mp[out[i]]
    print(''.join(out))
------------------------------------------------------------------------------------------------
95%通过,也没有说什么例子不通过...
发表于 2020-07-13 22:00:40 回复(0)