This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 3 years ago.
Is there a way to solve math equations that are in string format?
For example, I have
x = 2
y = 3
equations_str = ('x+y', 'x-y')
and I want a function that will give
results = (5, -1)
I want to do this because I want to have the equations as titles of figures, so they need to be strings.
I'm aware that a similar question was asked for java, but I'm not familiar enough with java so translate it to python.
Thanks!
Look into eval() https://www.geeksforgeeks.org/eval-in-python/ You can write statements and execute them.
eval example (interactive shell):
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
As Jam mentioned, you can do the following:
equations_str = (eval('x+y'), eval('x-y'))
The only way I can think of solving this problem is to take your equation, calculate it as a regular integer, and then convert it into a string using str(). Then you could put that result into an array before proceeding. The only thing is that this method won't work for large amounts, but if you only need a few, this should work. Hope this helps, Luke.
Try the sympify function of the sympy package. It lets you evaluate strings, but uses the eval function, so do not use it on unsanitized input.
Example:
>>> from sympy import sympify
>>> str_expr = "x**2 + 3*x - 1/2"
>>> expr = sympify(str_expr)
>>> expr
x**2 + 3*x - 1/2
>>> expr.subs(x, 2)
19/2
Related
This question already has answers here:
In what situation should the built-in 'operator' module be used in python?
(6 answers)
Closed 1 year ago.
from operator import add
n1 = add(2,3)
n2 = 2 + 3
Both return exactly the same number and I believe they also work in the same way. What are the advantages of using add() to calculate the sum of two numbers?
are there any cases where only one method is accepted?
Sometimes, you may want to pass the operator as a function somewhere, for example:
functools.reduce(operator.mul, [2,3,4,5]) # 120
You could, of course do something like:
functools.reduce(lambda x, y: x * y, [2,3,4,5])
but the operator reads better and is faster.
This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 6 years ago.
For example if i have:
x = '12'
print(int(x))
would turn x into an integer from a string.
What if I have:
x = '1+2'
And I want 3 as my output, how would I go about it since + cannot be converted into an int directly?
Use literal_eval which is much more safer than using eval. literal_eval safely evaluates an expression node or a string containing a python expression.
import ast
x = ast.literal_eval('1+2')
You could use the eval function to accomplish this; however, it should be noted that allowing unsanitized input into the eval function can pose a significant security risk. Here's an example:
x = '1 + 2'
print(eval(x))
Here you can use eval.
The usage is eval(expression[, globals[, locals]]).
Therefore
eval('1+2')
3
I have an equation in the form of a string, something like this:
(20 + 3) / 4
I can easily solve this equation by using eval(), but it will give me an answer of 5, not the correct answer of 5.75. I know this is because 20, 3, and 4 are integers. So I was wondering, is there any way to just tack a .0 onto the end of them? Or is there some other trick I should use to make eval() think they are floats?
Note: the numbers will not always be integers, so it would be great if the solution could detect if they are integers and treat them accordingly.
Note #2: I'm using python 2.7
Note #3: I already know that "Python 2 is legacy, Python 3 is the future."
Thanks!
You could use sympy to parse the string using sympy_parser.parse_expr and then solve/simplify it:
>>> from sympy.parsing import sympy_parser
>>> exp = '(20 + 3) / 4'
>>> sympy_parser.parse_expr(exp).round(2)
5.75
This would also work for other valid mathematical expressions.
This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 9 years ago.
Say I have 50,000 lines of string that contain simple mathematical expression (only +,- operator involve e.g. 1+2+3+5). I know that it is handy to use eval() in Python to evaluate those strings. However, the program is not efficient enough. I ran the cProfile and found most of the bottleneck is from the eval function (around 2.5 secs in 50,000 lines case). I've tried to write my own evaluation parser but it perform even slower then the eval.
So, what I want to ask is if there are any way to fast evaluate mathematical expression strings or improve the performance of eval()? Third-party package cannot be used.
The original problem is like this
We have a string of digit like 1234567 and we can insert +,-,or nothing between the digits like 1+23-4+56-7. So there will be 3^(digit-1) combinations for a given number string
What I implement in Python to calculate and generate string like the following
import itertools
def gen_Eq(op, num):
temp = [None]*(2*len(num)-1)
temp[::2] = num
temp[1::2] = op
string = ''.join(temp)
return string
def cal_Eq(num_string):
op_list = tuple(itertools.product(['+','-',''],repeat=len(num_string)-1))
eq = list(map(gen_Eq,op_list,itertools.repeat(num_string,len(op_list))))
print map(eval,eq)
This approach is faster:
>>> import re
>>> split_numbers = re.compile(r'-?\d+').findall
>>> sum(int(x) for x in split_numbers('1+23-4+56-7'))
69
In my timings the sum expression takes 4.5 µs vs. 13 µs for eval('1+23-4+56-7')
Note, however, that it does not handle consecutive + and -, eg. 1-+2 or 1--2, or spaces: 1 - 2.
Is it possible in Python to calculate a term in a string?
For example:
string_a = "4 ** (3 - 2)"
unknown_function(string_a) = 4
Is this possible? Is there a function that mimics "unknown_function" in my example?
Just like sympy was a useful module for your last question, it can apply here:
>>> import sympy
>>> sympy.sympify("4**(3-2)")
4
and even
>>> sympy.sympify("2*x+y")
2*x + y
>>> sympy.sympify("2*x+y").subs(dict(x=2, y=3))
7
Note though that this will return sympy objects, and if you want to get an integer or a float out of it you should do the conversion explicitly:
>>> type(sympy.sympify("4**(3-2)"))
<class 'sympy.core.numbers.Integer'>
>>> int(sympy.sympify("4**(3-2)"))
4
I hacked together a recipe to turn string expressions into functions here which is kind of cute.
There is eval
eval(string_a)
# 4
But do not use this under any circumstances if string_a comes from anyone but you, because they can easily hack into your system and destroy your files!
Yes, you can use the eval function.
>>> string_a = "4 ** (3 - 2)"
>>> eval(string_a)
4
>>>
You can read more in the documentation
There is a module py-expression-eval, that does not depend on the use of eval. It can be used to evaluate strings as a mathematical expression, even symbolic expressions can be evaluated.
from py_expression_eval import Parser
parser = Parser()
expr = parser.parse("4 ^ (3 - 2)")
expr.evaluate({})
For the use with symbolic expressions see:https://axiacore.com/blog/mathematical-expression-evaluator-python/