import itertools
import math
import time
from time import time
from math import factorial
from math import sqrt
def pretty(string):
string=string.replace("(4)","4")
string=string.replace("factorial4","factorial(4)")
string=string.replace("sqrt4","sqrt(4)")
return string
def test(n):
start=time()
fails=0
for i in range(0,n+1):
if(fours(i))!=None:
print(fours(i))
else:
print("Failed: "+str(i))
fails+=1
return("\nFailed "+str(fails)+" out of "+str(n)+"\n\nTotal time: "+str(time()-start)[:4]+"\nAverage time: "+str((time()-start)/n)[:4])
def fours(goal):
operators = ['-','/','+','*','sqrt','^','factorial',"."]
brackets = ["{0}{1}{0}{2}{0}{3}{0}",
"({0}{1}{0}){2}{0}{3}{0}",
"({0}{1}{0}{2}{0}){3}{0}",
"({0}{1}({0}{2}{0})){3}{0}",
"(({0}{1}{0}){2}{0}){3}{0}",
"{0}{1}({0}{2}({0}{3}{0}))",
"{0}{1}(({0}{2}{0}){3}{0})",
"({0}{1}{0}){2}({0}{3}{0})"]
for combination in itertools.product(operators, repeat=3):
for bracket in brackets:
try:
formula = bracket.format("(4)", *combination).replace(".(4","(.4")
except ValueError:
pass
try:
if eval(formula)==goal:
return(pretty((formula + " = " + str(int(eval(formula))))))
except:
pass
print(test(20))
以下是“Four Fours”求解器的代码 难题。http://en.wikipedia.org/wiki/Four_fours
它基本上可以工作,但问题是它只能使用+ - / *运算符,因为它不能连续有两个运算符(像这样的解决方案(4-4)/ 4 + factorial(4)因为这个“+因子”部分而不被允许。。我能做什么(但会慢)将是这样的配对。 [' - ','/','+','*',' - sqt',' - ^',' - factor',' - 。','/ sqrt','/ ^','/ factorial ','/。','+ sqrt','+ ^','+ factorial','+。',' sqrt',' ^',' factorial',' 。']
这是太多的运营商。
我想做的是尝试这样的事情
formula = bracket.format(["(4)","(4*)","(4-)","(4/)"], *combination).replace(".(4","(.4")
除非此语法无效。
我该怎么做?
或者如果你有更好的想法(我相信你们中的一些人会这样做),我愿意接受建议。
答案 0 :(得分:2)
您可以尝试将其转换为修复前或修复后。您可以随时允许它使用['!','sqrt','。']。只有当至少有四个仍然可以在堆栈上推送时,才会使用'^'。只有当运算符多于数字(或类似的东西)时才会推送['+',' - ','/','*']。