def testVariablesStartingInE(self): self.assertAlmostEqual( 4.0, cexprtk.evaluate_expression("electroneg * 4", {"electroneg": 1.0})) self.assertAlmostEqual( 1e-3, cexprtk.evaluate_expression("1e-3", {"electroneg": 1.0}))
def testNegativeNumber(self): self.assertAlmostEqual(-1.0, cexprtk.evaluate_expression("-1.0", {"A": 1.0})) self.assertAlmostEqual(-1.0, cexprtk.evaluate_expression("-A", {"A": 1.0})) self.assertAlmostEqual(2.0, cexprtk.evaluate_expression("A--1", {"A": 1.0}))
def testNestedFunction(self): expression = 'floor(if(abs(2)<0, 0.8, A))' expect = 1.0 actual = cexprtk.evaluate_expression(expression, {'A': 1.5}) self.assertAlmostEqual(expect, actual) expression = 'floor(if(2<0, 0.8, if(ceil(A) > 1.9, -1.0, 3)))' expect = -1.0 actual = cexprtk.evaluate_expression(expression, {'A': 1.5}) self.assertAlmostEqual(expect, actual)
def testBooleanAnd(self): self.assertEqual( 1, cexprtk.evaluate_expression("A and B", { "A": 1.2, "B": 1 })) self.assertEqual( 0, cexprtk.evaluate_expression("A and B", { "A": 1.2, "B": 0 }))
def testBooleanNot(self): self.assertEqual(1, cexprtk.evaluate_expression("not(A)", {"A": 0.0})) self.assertEqual( 0, cexprtk.evaluate_expression("not(A and B)", { "A": 1.2, "B": 1 })) self.assertEqual( 0, cexprtk.evaluate_expression("not(abs(A))", { "A": 1.2, "B": 1 }))
def post(self, request): """ Evaluates if an expression is valid and either returns a validation error or the evaluation of the given expression """ data = request.data if "expression" in data and data["expression"]: expression = data["expression"] try: result = evaluate_expression(expression, {}) except (SyntaxError, ParseException): return Response( data={ "validation_error": ("Please check the validity of the" " mathematical expression and try again") }, status=status.HTTP_400_BAD_REQUEST, ) return Response(data={"result": result}, status=status.HTTP_200_OK) return Response( data={ "validation_error": "expression can not be blank or missing" })
async def bc(self, ctx, *, args): args = args.strip(' `') for banned_word in ['open', 'read', 'write', 'getline']: if banned_word in args: raise errors.CheckFailure(f'Banned word found') try: await ctx.bot.say(str(cexprtk.evaluate_expression(args, {}))) except: raise errors.BadArgument(f'Invalid expression')
def func(self): equation = self.attributes['equation'] z = lambda a, b: cexprtk.evaluate_expression(equation, {'x': a, 'y': b}) for i in range(0, 20): x = i * 0.025 for j in range(0, 20): y = j * 0.025 self.planeVertex.append([x, y, z(x, y)]) self.planeVertex.append([x, y + 0.025, z(x, y + 0.025)]) self.planeVertex.append([x + 0.025, y, z(x + 0.025, y)]) self.planeVertex.append([x + 0.025, y, z(x + 0.025, y)]) self.planeVertex.append([x + 0.025, y + 0.025, z(x + 0.025, y + 0.025)]) self.planeVertex.append([x, y + 0.025, z(x, y + 0.025)])
def evaluate_math(message): if type(message) == str: content = message else: content = message.content if "what is " in content: msg = content.partition("what is ")[2] else: msg = content.partition(": ")[2] try: ans = cexprtk.evaluate_expression(msg, {}) except: return [None, "sorry i don't understand that math expression :("] return [str(ans)]
def version(question_code, inputs, answer_code): parse_out = parse.parse(question_code, inputs) vars = parse_out["vars"] kwargs = dict() for i in range(len(inputs)): input = inputs[i][0] if isinstance(input, list): n2 = len(input) - 1 n1 = len(inputs[i]) index = randint(1, n2) for j in range(n1): key = inputs[i][j][0] value = inputs[i][j][index] kwargs[key] = value else: key = inputs[i][0] value = round( inputs[i][1] + (inputs[i][2] - inputs[i][1]) * randint(0, inputs[i][3]) / inputs[i][3], dec) # Do not unnecessarily put a zero in the tenths place. value = int(value) if value == int(value) else value kwargs[key] = value question = question_code.format(**kwargs) # First, see if this answer is numerical and unrandomized try: answer = float(answer_code) except ValueError: # Next, see if the answer is for randomized T/F or fill-in-the-blank questions if answer_code in vars: answer = kwargs[answer_code] if answer == True: answer = "T" if answer == False: answer = "F" # Finally, the answer must be for randomized numerical question else: answer = round(cexprtk.evaluate_expression(answer_code, kwargs), dec) return dict(question=question, answer=answer)
def solve(self, expr, isin, date, values=None): """This function will solve the Expression expr with values values""" logger = logging.getLogger(__name__) ret = None try: msg = f"Starting solve {expr} with {isin}, {date}, {values}" logger.debug(msg) self.gc.writeJobStatus("Running", statusMessage=msg) if (values is not None): ret = cexprtk.evaluate_expression(expr, values) self.gc.writeJobStatus("Running", statusMessage=msg + " - DONE") logger.debug(msg + " - DONE") except Exception as e: logger.exception('Crash!', exc_info=e) self.gc.numErrors += 1 self.gc.errMsg += "Crash solving {expr} with {isin}, {date}, {values}; " return ret
print("An error was encountered. The following trace was generated: " "{}".format(e)) user_input = '0' while user_input != 'q': user_input = input('\nChoose option "a" or "b", or type "q" to quit: ') if user_input == 'a': print('You have chosen part a.') try: x_input = input('Enter a value for x: ') if parser_installed: # parses mathematical expressions in the input field x = cexprtk.evaluate_expression(x_input, {}) else: x = float(x_input) except ValueError: print("Invalid input. \"{}\" is not a valid " "value.".format(x_input)) except ParseException: print("Invalid syntax: \"{}\" Please make sure your function is " "correctly formatted using brackets. e.g. 'sqrt(x)' " "rather than 'sqrtx'".format(x_input)) try: # allows the user to input the number of terms to iterate over N = int(input('Enter a value for N: '))
def testParseException(self): with self.assertRaises(cexprtk.ParseException): cexprtk.evaluate_expression("(1 + 1", {})
def testAddition(self): self.assertAlmostEqual( 3.57, cexprtk.evaluate_expression("A+B", { "A": 1.23, "B": 2.34 }))
def testIf(self): self.assertEqual( 2, cexprtk.evaluate_expression("if ( A>1 , 2, 3 )", {"A": 3})) self.assertEqual( 3, cexprtk.evaluate_expression("if ( not(A>2), 2, 3 )", {"A": 3}))
def testSubtraction(self): self.assertAlmostEqual( -6.33, cexprtk.evaluate_expression('A - 12', {"A": 5.67}))
def testMultiplication(self): self.assertAlmostEqual( 6.9741, cexprtk.evaluate_expression('A * B', { "A": 1.23, "B": 5.67 }))
def testDivision(self): self.assertAlmostEqual(4.065040650406504, cexprtk.evaluate_expression('5/A', {"A": 1.23}))
def testSqrt(self): expression = '5+sqrt(3-B)-0' self.assertAlmostEqual( math.sqrt(2) + 5, cexprtk.evaluate_expression(expression, {"B": 1}))
def testPower(self): self.assertAlmostEqual(8.0, cexprtk.evaluate_expression('2^A', {"A": 3}))