描述
计算24点是种扑克牌益智游戏,随机抽出4张牌,通过加、减、乘、除运算得到整数24,其中,小写joker表示小王,大写JOKER表示大王
要求实现:输入4张牌,输出一个算式,算式的结果为24点
详细说明:1、输入4张牌为字符串形式,以一个空格隔开,如果输入的4张牌中包含大小王,则输出字符串“ERROR”,表示无法运算;
2、输出的算式格式为4张牌通过±*/四个运算符相连,中间无空格
3、如果无法得出24,则输出“NONE”表示无解;
输入描述:
输入4张牌为字符串形式,以一个空格隔开;
输出描述:
输出怎么运算得到24,如果无法得出24,则输出"NONE"表示无解,如果输入的4张牌中包含大小王,则输出字符串“ERROR”,表示无法运算;
解题思路:本题不存在子问题模板化适配,所以必须穷举法。先评估下暴力求解时问题规模:4个数字,3个运算符。对数字来说,4321 = 24种排列;对于运算符,4的3次方=64种。所以整体问题规模是2464 = 1536 个计算组合。相比c++/java,用python的eval、笛卡尔积函数product跟生成排序序列的permutation函数缩减代码行数
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)&nbs**bsp;(‘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)