原题链接:速算24点
itertools是一个迭代器模块,具体功能详见 https://docs.python.org/3/library/itertools.html#
参考代码:
import itertools class Over(Exception): # 定义异常 pass user_old = input().split() for i,j in enumerate(user_old): # 将字母转换为数字 if j == "A": user_old[i] = "1" elif j == "J": user_old[i] = "11" elif j == "Q": user_old[i] = "12" elif j == "K": user_old[i] = "13" else: # else可写可不写,个人感觉不写很怪 continue try: for user in itertools.permutations(user_old): for l_bracket in range(3): l = ["", "", ""] l[l_bracket] = "(" for r_bracket in range(l_bracket, 3): if l_bracket == 0 and r_bracket == 2: continue r = ["", "", ""] r[r_bracket] = ")" for AO in itertools.product(["+", "-", "*", "/"], repeat = 3): try: # 0-3为数字,4-6为算术运算符,7-9为左括号,10-12为右括号 if(eval("{7}{0}{4}{8}{1}{10}{5}{9}{2}{11}{6}{3}{12}". format(user[0], user[1], user[2], user[3], AO[0], AO[1], AO[2], l[0], l[1], l[2], r[0], r[1], r[2])) == 24): raise Over #如果等于24,抛出异常,这里作用是直接跳出所有循环,类似c++中的goto except ZeroDivisionError: continue # 除数为零直接跳过 r.clear() l.clear() else: # for - else 当for循环中的if每次都不成立时,执行else。类似还有while - else print("N") except Over: # 接受上面抛出的Over,打印Y print("Y")
ps:前面的判断字母那部分for代码,再python3.10及上还可以用 match - case 代替,类似于c++中的switch - case,其中case _ 相当于c++ 的default
match详见 https://docs.python.org/zh-cn/3/whatsnew/3.10.html#pep-634-structural-pattern-matching
注意:目前蓝桥杯acm编译器还不支持match - case,用了会显示答案错误
import itertools class Over(Exception): #定义异常 pass user_old = input().split() for i, j in enumerate(user_old): match j: case "A": user_old[i] = "1" case "J": user_old[i] = "11" case "Q": user_old[i] = "12" case "K": user_old[i] = "13" case _: continue # 在这里一样可以不写 try: for user in itertools.permutations(user_old): for l_bracket in range(3): l = ["", "", ""] l[l_bracket] = "(" for r_bracket in range(l_bracket, 3): if l_bracket == 0 and r_bracket == 2: continue r = ["", "", ""] r[r_bracket] = ")" for AO in itertools.product(["+", "-", "*", "/"], repeat = 3): # 0-3为数字,4-6为算术运算符,7-9为左括号,10-12为右括号 try: if(eval("{7}{0}{4}{8}{1}{10}{5}{9}{2}{11}{6}{3}{12}". format(user[0], user[1], user[2], user[3], AO[0], AO[1], AO[2], l[0], l[1], l[2], r[0], r[1], r[2])) == 24): raise Over #如果等于24,抛出异常,这里作用是直接跳出所有循环,类似c++中的goto except ZeroDivisionError: continue #除数为零直接跳过 r.clear() l.clear() else: #for - else 当for循环中的if每次都不成立时,执行else。类似还有while - else print("N") except Over: #接受上面抛出的Over,打印Y print("Y")
0.0分
1 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复