Calculating strings as values - python

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/

Related

Answer is only printing .0 instead of .00 in python [duplicate]

I have a function taking float arguments (generally integers or decimals with one significant digit), and I need to output the values in a string with two decimal places (5 → 5.00, 5.5 → 5.50, etc). How can I do this in Python?
Since this post might be here for a while, lets also point out python 3 syntax:
"{:.2f}".format(5)
You could use the string formatting operator for that:
>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'
The result of the operator is a string, so you can store it in a variable, print etc.
f-string formatting:
This was new in Python 3.6 - the string is placed in quotation marks as usual, prepended with f'... in the same way you would r'... for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside braces f'some string text with a {variable} or {number} within that text' - and Python evaluates as with previous string formatting methods, except that this method is much more readable.
>>> foobar = 3.141592
>>> print(f'My number is {foobar:.2f} - look at the nice rounding!')
My number is 3.14 - look at the nice rounding!
You can see in this example we format with decimal places in similar fashion to previous string formatting methods.
NB foobar can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'.
Going forward, with new code I prefer f-strings over common %s or str.format() methods as f-strings can be far more readable, and are often much faster.
String Formatting:
a = 6.789809823
print('%.2f' %a)
OR
print ("{0:.2f}".format(a))
Round Function can be used:
print(round(a, 2))
Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.
b = round(a, 2)
print(b)
Use round() - mostly for display purpose.
String formatting:
print "%.2f" % 5
If you actually want to change the number itself instead of only displaying it differently use format()
Format it to 2 decimal places:
format(value, '.2f')
example:
>>> format(5.00000, '.2f')
'5.00'
Using python string formatting.
>>> "%0.2f" % 3
'3.00'
Shortest Python 3 syntax:
n = 5
print(f'{n:.2f}')
In Python 3
print(f"{number:.2f}")
A shorter way to do format.
I know it is an old question, but I was struggling finding the answer myself. Here is what I have come up with:
Python 3:
>>> num_dict = {'num': 0.123, 'num2': 0.127}
>>> "{0[num]:.2f}_{0[num2]:.2f}".format(num_dict)
0.12_0.13
I faced this problem after some accumulations. So What I learnt was to multiply the number u want and in the end divide it to the same number. so it would be something like this: (100(x+y))/100 = x+y if ur numbers are like 0.01, 20.1, 3,05.
You can use number * (len(number)-1)**10 if your numbers are in unknown variety.
If you want to get a floating point value with two decimal places limited at the time of calling input,
Check this out ~
a = eval(format(float(input()), '.2f')) # if u feed 3.1415 for 'a'.
print(a) # output 3.14 will be printed.
Using Python 3 syntax:
print('%.2f' % number)

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

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

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

Python - Convert intergers to floats within a string

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.

Sympy won't evaluate 2x but will evaluate x*2

I'm using Sympy's sympify function to simplify 2 expressions so I can compare them for equality.
For example:
expr1 = sympify("(2 * x) + (x + 10)")
expr2 = sympify("(x + 10) + (x * 2)")
if expr1 == expr2:
print "Congrats those are essentially the same!"
However when using the form 2x as apposed to x*2 i get a parse exception eg:
expr1 = sympify("2x + (x + 10)")
Is there any way I can get sympy to understand the 2x form ?
If not, is there any other library that will allow this form ?
Well, you could modify the sympy lexer (or parser / grammar / whatever).
You could also wrap it with a function that transformed your input strings for you, using something like this:
>>> import re
>>> expr = '2x + 1'
>>> re.sub(r"(\d+)(\w+)", r"(\1 * \2)", expr)
'(2 * x) + 1'
But ask yourself why this notation isn't there to begin with.
For example, all of these are valid python, and though it's been a long while since I messed with sympy, I bet they mean something besides multiplication in sympy too:
0x32 # hex for 50
5e-3 # 0.005
2j # 2 * sqrt(-1) (so that one *is* multiplication, but by 1j, not j!)
15L # 15 (L used to represent long integers in python)
And what does x2 mean? Is it a variable named x2 or does it mean (x * 2). I purposely left this case out of the regular expression above because it's so ambiguous.
The development version of SymPy has the ability to parse such expressions. See http://docs.sympy.org/dev/modules/parsing#sympy.parsing.sympy_parser.implicit_multiplication_application. It is still not enabled by default in sympify, because sympify only does very basic extensions to the Python syntax (i.e., wrapping of numeric literals and undefined names, and converting ^ to **). But there is an example there that shows how to use it.
Note that this currently also applies implicit function application as well. Probably the two functionalities should be split up.
EDIT: Those functions are being split up in a pull request.

Categories

Resources