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 人评分
1113题解浏览:823 |
核桃的数量 (C语言代码)浏览:726 |
C语言程序设计教程(第三版)课后习题1.6 (C语言代码)浏览:524 |
Hello, world! (C语言代码)浏览:766 |
敲七 (C++代码)浏览:1119 |
C语言程序设计教程(第三版)课后习题5.4 (C语言代码)浏览:501 |
A+B for Input-Output Practice (II) (C语言代码)浏览:622 |
孤独的骑士 (C语言代码)浏览:1416 |
非常简单的算法,题解1049:C语言程序设计教程(第三版)课后习题11.1 (C语言代码)浏览:639 |
C语言程序设计教程(第三版)课后习题10.7 (C++代码)浏览:666 |