How to convert '1+2' into an int in python [duplicate] - python

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

Related

How do you convert a string containing an operation into a numerical value [duplicate]

This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 1 year ago.
I need to convert a string variable in the form of 'x / y', where x and y are arbitrary values in this string, into a numerical value. I'd assume that, using python, simply doing float('x/y') would allow for the interpretation of the division operation and thus yield a numerical value as the response, but instead, I am met with the following error:
ValueError: could not convert string to float: '7/100' (7 and 100 were the arbitrary values here)
Which suggests that this method is invalid. Is there any other way of doing this ? I thought of converting 'x' into an integer, then 'y' into an integer, and dividing the two integer values, but surely there's a better way of doing this.
>>> a = '4/10'
>>> float(eval(a))
0.4
But I would be careful with eval . It's not safe, you could probably use ast.literal_eval() instead

Python3 - solve math equations that are in string format [duplicate]

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

Code notes: Explaining the what is happening in the code [duplicate]

This question already has answers here:
What does Python's eval() do?
(12 answers)
Closed 4 years ago.
I am a newbie developer. I have used the code below but I would like to understand how the last line works, can someone please explain to me the last line return eval(((str(a)+"*")*b)[:-1]) of the code?
def power(a,b):
if b == 0:
return 1
else:
return eval(((str(a)+"*")*b)[:-1])
eval evaluates python code or lets Python program run Python code within itself.
example:
CODE:
a = 15
eval('print(a + 3)')
OUTPUT:
18
when you return the following
eval(((str(a)+"*")*b)[:-1])
what you basically doing is this( for example if you are computing power(2,5)):
str(a) -> changes the value of a to string. in this case "2"
str(a)+"*" -> concatinate the above string to the multiplication sign. now we have "2*"
(str(a)+"*")*b) -> duplicates the above string b times. That is "2*"+"2*"+"2*"+"2*"+"2*", that is five times and now you have "2*2*2*2*2*"
But as you can see there is an extra "*" at the end. To remove this one we use [:-1]. what this basically doing is select all except the last one. ":" basically means all.
so the final expression to be evaluated is "2*2*2*2*2". which is 2^5.
The best way is to use a**b for computing power. However, if you want to use eval then consider joining the string in this way: eval('*'.join(str(a)*b)). In this, str(a) will convert integer a to string a then *b will repeat the a b times and finally the '*'.join() will join all the a's together with * in between and create a string something like a*a*a*a. eval will then evaluate the string as if it is an expression.
return eval(((str(a)+"*")*b)[:-1])
is equivalent to
a_str=str(a) # convert a in STRING
a_star=a_str+"*" # concat the string a_str with "*"
a_repeted=a_star*b # repeat a_star "b" times
exp=(a_repeted)[:-1] # get all a_repeted car except the last on (ex 3*3*3*3 for a=3 and b=4)
res=eval(exp) # evalutate the expression
return res
it'is equivalent to (really better ;-) !) :
def power(a,b):
return a ** b
A terrible idea, as others have said - if you're a newbie, consider finding a better guide!
eval reads a string and evaluates it as if it were not (as if it is not in quotes). So we construct a string of a ** b (ie a^b), and ask Python to read it, then return all but the last character. Pretty pointless but there you go.
eval() is never a good idea to use. Read about its dangerous behaviour here.
You just need ** operator which is equivalent to ^ (raise to) operator you see in other languages:
def power(a,b):
return a ** b

Better way to evaluate mathematical expression in python? [duplicate]

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.

Calculating strings as values

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/

Categories

Resources