挺强的算24程序,支持2重()
2021/12/6 20:46:53
本文主要是介绍挺强的算24程序,支持2重(),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
# 1-((2+3)*4) = -19 ptns = '''N?N?N?N N?N?N?N N?N?(N?N) N?(N?N)?N N?(N?N?N) N?(N?(N?N)) N?((N?N)?N) (N?N?N)?N (N?(N?N))?N ((N?N)?N)?N'''.splitlines() def permute(x): def pmt(x, y, n, i): if i == n: yield y for j in range(n): if x[j] == 99: continue y[i] = s = x[j]; x[j] = 99 yield from pmt(x, y, n, i + 1) x[j] = s n = len(x) return pmt(x, list(range(n)), n, 0) x = ('1 2 3 4' if 1 else input()).split() if len(x) != 4: exit() for n_ in permute(x): for p_ in permute(['+', '-', '*']): for t in ptns: e = ''; n = n_.copy(); p = p_.copy() for u in t: if u == '?': e += p.pop() elif u == 'N': e += n.pop() else: e += u print(e, '=', eval(e))
N?N?(N?N)可是自动生成滴:
import ply.lex as lex # pip install ply import ply.yacc as yacc from functools import reduce tokens = ('WORD',); t_WORD = r'[\w+\+\-\*\/\(\)\?]'; literals = (':', ';') t_ignore = ' \t\r\n' def t_error(t): raise SyntaxError() d = {} def p_1(p): "rules : rule" def p_2(p): "rules : rule rules" def p_4(p): "rule : WORD ':' words ';'" k = p[1]; v = d.get(k, []); v.append([p[3]]) d[k] = v def p_5(p): "words : WORD"; p[0] = [p[1]] def p_6(p): "words : WORD words"; p[0] = [p[1]] + p[2] lexer = lex.lex() istr = ''' e : N ; e : N ? e ; e : N ? (e) ; e : (e) ? N ; ''' try: yacc.yacc().parse(istr) except SyntaxError: quit() seen = set() def gen(s): if len(s) > 11: return expanded = False for i in range(len(s)): w = s[i] for r in d.get(w, []): expanded = True gen(s[:i] + r[0] + s[i + 1:]) e = reduce(lambda a,b:a+b, s) if e in seen: return seen.add(e) if not expanded: if e.count('?') == 3: print(e) gen(['e'])
我吹了一点牛。(N)我干不掉,于是串替换成N,再一看有重复的,手工删掉了。
这篇关于挺强的算24程序,支持2重()的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-22项目:远程温湿度检测系统
- 2024-12-21《鸿蒙HarmonyOS应用开发从入门到精通(第2版)》简介
- 2024-12-21后台管理系统开发教程:新手入门全指南
- 2024-12-21后台开发教程:新手入门及实战指南
- 2024-12-21后台综合解决方案教程:新手入门指南
- 2024-12-21接口模块封装教程:新手必备指南
- 2024-12-21请求动作封装教程:新手必看指南
- 2024-12-21RBAC的权限教程:从入门到实践
- 2024-12-21登录鉴权实战:新手入门教程
- 2024-12-21动态权限实战入门指南