执行cos(x)会使程序卡死,如果x不在[-9,9]范围内

2024-04-25 00:50:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这是我用来解输入计算器的方程的代码。它似乎在大多数情况下工作正常,但如果我尝试输入一个值在[-9,9]之外的函数(cos、sin等),程序就会冻结。你知道吗

我做错了什么?你知道吗

字符串示例:

  • 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

我尝试使用的任何函数似乎都是如此。你知道吗


Tags: 函数fromimportreinputsearchdefmath
1条回答
网友
1楼 · 发布于 2024-04-25 00:50:51

问题在于你的循环:去掉exec它仍然会挂起。请尝试以下操作:

from __future__ import division
from math import *
def solution_handler(self, input):
    return eval(input)

相关问题 更多 >