def eval_formula(formula):
import math
import ast
import operator as op
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
ast.USub: op.neg}
def eval_expr(node):
if isinstance(node, ast.Num): # <number>
return node.n
elif isinstance(node, ast.operator): # <operator>
return operators[type(node)]
elif isinstance(node, ast.UnaryOp): # <unaryop> <expr>
return eval_expr(node.op)(eval_expr(node.operand))
elif isinstance(node, ast.BinOp): # <expr> <operator> <expr>
return eval_expr(node.op)(eval_expr(node.left), eval
def evaluate(s):
return eval(s)
evaluate("1+2")
import re
def calc(x):
x = re.sub(r'\s+','',x)
x = re.sub(r'([\d\.]+)([\+\-\*\/\^√])([\d\.]+)',r'\1\2\3',x)
return eval(x.replace('^','**').replace('√','sqrt'))
def eval_math(text):
pass
eval_math('1+2*3')
eval_math('(1+2*3)/(1+2)')
s = '1 + 2 + 3 - 4 + 5 - 6 + 7 + 8 - 9 + 10'
l = s.split(' ')
def caculate(l):
if l[1] == '+':
return float(l[0]) + float(l[2])
elif l[1] == '-':
return float(l[0]) - float(l[2])
elif l[1] == '*':
return float(l[0]) * float(l[2])
elif l[1] == '/':
return float(l[0]) / float(l[2])
elif l[1] == '**':
return float(l[0]) ** float(l[2])
elif l[1] == '//':
return float(l[0]) // float(l[2])
elif l[1] == '%':
return float(l[0]) % float(l[2])
elif l[1] == '&':
return
def eval(expression):
pass
# 用eval函数调用
eval('1+2+3')
# 用eval函数输入乘方运算
eval('1**2')
# 用eval函数输入平方根
eval('1**0.5')
# 用eval函数输入平方根乘方
eval('1**0.5**2')
++
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
int num1, num2;
char op;
while (cin >> str)
{
for (int i = 0; i < str.length(); i++)
if ((str[i] == '+') || (str[i] == '-') || (str[i] == '*') || (str[i] == '/'))
{
op = str[i];
str[i] = ' ';
break;
}
num1 = stoi(str);
cin >> num2;
switch (op)
{
case '+':cout << num1 + num2; break;
case '-':cout << num1 - num2; break;
case '*':cout << num1 * num2; break;
case '/':cout << num1 /
def calculate(text):
return eval(text.replace('^', '**'))
calculate('1+2')
def cal_math(text):
try:
print(eval(text))
except:
print("语法错误!")
cal_math("1+2+3")
def eval(s):
return eval(s)
eval('1 + 2')
def calculate(expression):
return eval(expression)
def cal(a, b, op='+'):
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
return a / b
cal(1, 2, '+')
def caculate(s):
return eval(s)
caculate("1+2+3")
def math_eval(math_exp):
return eval(math_exp)
math_eval('3 + 5')
def calc(s):
return eval(s)
calc('1+2')
def calculate(string):
operator = {
'+': (1, lambda a, b: a + b),
'-': (1, lambda a, b: a - b),
'*': (2, lambda a, b: a * b),
'/': (2, lambda a, b: a / b),
'//': (2, lambda a, b: a // b),
'%': (2, lambda a, b: a % b),
'**': (3, lambda a, b: a ** b)
}
stack = []
for item in string.split(' '):
if item in operator:
while stack and operator[item][0] <= operator[stack[-1]][0]:
a, b = stack.pop(), stack.pop()
stack.append(operator[b][1](a, b))
stack.append(item)
elif item:
stack.append(float(item))
while len(stack) != 1:
a
def eval(string):
# 将输入的字符串表达式转换成python能识别的数学表达式
string = string.replace('^', '**') # 将'^'替换成'**'
string = string.replace('√', 'math.sqrt(')
string = string.replace(' ', '') # 将字符串中的空格去掉
# 使用eval进行计算
return eval(string)
// (1 + 2) * 3
// -2 + 3
// -2 + 3 / 5
// 8 ** 2
// 把中缀表达式转化为后缀表达式
// 后缀表达式计算
// 实现链式调用,把中缀表达式转成后缀表达式的过程可以使用函数式编程的概念来实现
class Arithmetic {
constructor(input) {
this.input = input
this.stack = []
this.output = []
}
infixToPostfix() {
// ...
return this
}
calculate() {
// ...
return this
}
}
from math import *
def eval(s):
return eval(s)
eval("1+2*(sqrt(9) + 5/7)")
import re
import sys
import math
def get_priority(op):
if op in ['*', '/']:
return 2
elif op == '**':
return 3
else:
return 1
def get_op(op):
if op == '+':
return lambda x, y: x + y
elif op == '-':
return lambda x, y: x - y
elif op == '*':
return lambda x, y: x * y
elif op == '/':
return lambda x, y: x / y
elif op == '**':
return lambda x, y: x ** y
elif op == 'sqrt':
return lambda x: math.sqrt(x)
def cal(s):
sl = re.split(r'([()+\-*/])', s)
while '' in sl:
sl.remove('')
num = []
op = []
for i in sl:
if i in ['(',
def parse(str):
return eval(str)
parse("1+2")
def calculate(s):
print(eval(s))
def eval_expr(expr):
# TODO: YOUR CODE HERE
expr_list = expr.split()
if len(expr_list) == 1:
return int(expr_list[0])
else:
for i in range(len(expr_list)-1, 0, -1):
if expr_list[i] == '+' or expr_list[i] == '-':
expr_list[i-1] = str(eval(''.join(expr_list[i-1:i+2])))
expr_list.remove(expr_list[i])
expr_list.remove(expr_list[i])
for i in range(len(expr_list)-1, 0, -1):
if expr_list[i] == '*' or expr_list[i] == '/':
expr_list[i-1] = str(eval(''.join(expr_list[i-1:i+2])))
expr_list.remove(expr_list[i])
expr_list
def jisuan(a):
a=a.replace("**","^")
a=a.replace("//","/")
try:
count=eval(a)
except Exception:
count="输入有误"
return count
jisuan('1+2')
def math_compute(expr):
expr = expr.replace(' ', '') #去除空格
return eval(expr)
math_compute('1+2*3**2') #求1+2*3^2的结果
def eval_cal(text):
return eval(text)
eval_cal('1+2*(3+4)')
from operator import add, sub, mul, truediv, pow
from math import sqrt
def calculate(expression):
return eval(expression)
calculate('1+2')
def evaluate(expression):
return eval(expression)
evaluate("2 + 3") #5
def compute(expr):
return eval(expr)
compute('1+2')
import re
def calculate(text):
return eval(re.sub('[a-zA-Z]|\s+', '', text))
calculate('1+2*3')
++
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
double a, b, c;
char o, o2;
cin >> a >> o >> b >> o2 >> c;
switch (o)
{
case '+':
a = a + b;
break;
case '-':
a = a - b;
break;
case '*':
a = a * b;
break;
case '/':
a = a / b;
break;
case '^':
a = 1;
for (int i = 0; i < b; i++) a = a * b;
break;
case '$':
a = 0;
for (int i = 0; i < b; i++) a = a + b;
break;
default:
break;
}
switch (o2)
{
#
#include <iostream>
#include <string>
#include <stack>
#include <sstream>
#include <cmath>
using namespace std;
int main()
{
string s = "2+3*4-5^2";
stringstream ss;
stack<int> nums;
stack<char> signs;
int num;
char sign;
while (!s.empty())
{
if (isdigit(s.back()))
{
ss << s.back();
s.pop_back();
if (s.empty() || !isdigit(s.back()))
{
ss >> num;
nums.push(num);
ss.clear();
}
}
else
{
if (s.back() == '^')
{
int num = nums.top();
nums.pop();
num = pow(num, 2);
nums.push(num);
}
from sympy import *
def calculate(exp):
x = Symbol('x')
return eval(str(exp))
calculate('x**2+2*x')
def check_math_expression(expression, check_syntax=True, print_result=True):
import math
import re
if check_syntax:
if not re.match(r'^[\+\-\*\/\(\)0-9\.\s]+$', expression):
print('语法错误!')
return False
expression = expression.replace(' ', '')
# 括号中的计算
while re.findall(r'\([^()]+\)', expression):
expression = re.sub(r'\([^()]+\)', str(eval(re.findall(r'\([^()]+\)', expression)[0])), expression, count=1)
# 乘方计算
while re.findall(r'\d+\^\d+', expression):
expression = re.sub(r'\d+\^\d+', str(eval(re.findall(
def recognize_text(img):
"""Recognize text in the image.
Args:
img: The input image.
Returns:
Text in the image.
"""
img = img.convert('L')
image = img.resize((200, 80))
image = np.array(image)
# 二值化
threshold = 160
table = []
for i in range(256):
if i < threshold:
table.append(0)
else:
table.append(1)
image = image.point(table, '1')
# Normalize the image to 0 and 1.
image = image * (1.0 / 255.0)
# 黑白反转
image = 1 - image
# 切割图片
image = image.reshape([1, 80, 200, 1])
image = image.astype(np.float32)
# Predict.
out_
def arithmetic(str):
return eval(str)
arithmetic('5+3*5-5/5+5*5')
# 40.0
def str2float(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
def fun(s):
return {'+':add, '-':sub, '*':mul, '/':div}[s]
def calc(s):
num, funs, n = 0, [], 0
num = reduce(fn, map(char2num, s.replace('.', '')))
for c in s:
if c in '+-*/':
funs.append(fun(c))
n -= 1
return reduce(lambda x, y: y(x, nums[n]), funs, num)
return calc(s)