from math import *
def solution_handler(self, input):
while re.search(r'(?<!.)(d+)(?!.)(d*)', input):
rx = re.search(r'(?<!.)(d+)(?!.)(d*)', input)
input = input[:rx.start()] + rx.group() + ".0" + input[rx.end():]
exec "solution = " + input
return solution
这是我用来解我正在使用的计算器中输入的方程的代码。大多数情况下,它似乎工作得很好,但如果我试图输入一个函数(cos, sin等),其值在[-9,9]之外,程序就会冻结。
我做错了什么?
字符串的例子:
-
exec "solution = " + "6*cos(6)" -> solution = 5.761 ...
-
exec "solution = " + "7/cos(8/2)" -> solution = -10.709 ...
-
exec "solution = " + "sin(12) + 3" -> Freeze
-
exec "solution = " + "abs(-50) / 2" -> Freeze
这似乎是我尝试使用的任何函数的情况
问题是你的循环:删除exec
,它仍然会挂起。试试这个:
from __future__ import division
from math import *
def solution_handler(self, input):
return eval(input)