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', '-.', '/sqrt', '/^', '/factorial', '/.', '+sqrt', '+^', '+factorial', '+.', '*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
它主要起作用,但输入量越大,速度就越慢。
我想做的是制作一个较小的运营商列表,就像这样。
['-','/','+','*','sqrt','^','factorial',"."]
但要做到这一点,我需要做到这一点,所以程序可以有一个方法将两个运算符放在一行 所以它可以得到这样的结果。
4/4+factorial(4)/sqrt(4) = 13
请注意,这些因子在他们+符号后立即出现。
我之前询问过如何做到这一点,并且有人建议我制作互斥的列表,以便不会在同一个列表中的运营商一个接一个地放置。
问题在于,如果不重写我的代码,我似乎无法找到一种有效的方法。
如果有人有这么好的方法(或者更好的方法来完成同样的事情),请告诉我。
另外,我希望程序能够将两个四肢放在一起以制作像44这样的数字,但这样做会给我带来同样的问题。
示例:当我做0到20时,我得到了
(4-(4-4))-4 = 0
(4-(4-4))/4 = 1
(4-(4-4))-sqrt(4) = 2
4-((4-sqrt(4))/sqrt(4)) = 3
4-((4-4)/4) = 4
4-((4/4)-sqrt(4)) = 5
4-((4-4)-sqrt(4)) = 6
4-((4/4)-4) = 7
4-((4-4)-4) = 8
4-((4-factorial(4))/4) = 9
(4-(4-4))/(.4) = 10
但是当我使用系统时,我想使用
(4-(4-4))-4 = 0
(4-(4-4))/4 = 1
4-((4+4)/4) = 2
(4+4+4)/4 = 3
4-((4-4)/4) = 4
(4+4*4)/4 = 5
(4+4)/4+4 = 6
4-((4/4)-4) = 7
4-((4-4)-4) = 8
4/4+4+4 = 9
Failed: 10
数字10失败是因为它不能在除法符号后面加上小数,而数字9是不同的,因为因子不能在 -
之后答案 0 :(得分:3)
你的程序需要太长时间来实现更大的目标,因为它会尝试采用3628804的阶乘.Python会在很长一段时间内咀嚼它。这在评估期间发生:
如果它能够实现这一目标,那么在此之后还有更难的事情要做。它不会在你的一生中完成。
您需要找到避免此类计算的方法。避免函数的组合(如阶乘(阶乘(x))可能就足够了。避免问题的一种简单方法是编写一个中间函数,比如“lfact”,来限制计算阶乘的大小.lfact将测试参数,如果太大会引发异常或返回None,否则调用math.factorial。您将在eval'd公式中调用替换lfact函数。