Format a mathematical expression from user input to python - python

I want to be able convert the input of a mathematical expression from a user to the python format for math expressions. For example if the user input is:
3x^2+5
I want to be able to convert that into
3*x**2+5
so that I can user this expression in other functions. Is there any existing library that can accomplish this in Python?

You can use simple string formatting to accomplish this.
import re
expression = "3x^2+5"
expression = expression.replace("^", "**")
expression = re.sub(r"(\d+)([a-z])", r"\1*\2", expression)
For more advanced parsing and symbolic mathematics in general, check out SymPy's parse_expr.

Related

Discord.py extracting integers and floats within message content

I am currently working on a bot within Discord and in one of the functions I require it to be able to extract integers and floats from message content while ignoring anything else. I am wondering what would be the best way to do this while still keeping in mind mathematical operations (e.g if a message said "27+3 whats good dude" I would expect the variable to return "30"). Currently I am just extracting the whole message content and using that for my input however say someone were to put any text after they put the numbers (e.g "594 what's up man") it throws off the rest of the function as it requires a stripped integer or float value.
Here is the sample of the code that is currently being thrown off whenever a non-integer input is entered
and here are both examples of what I want the bot to require as correct inputs
Expecting 373:
Expecting 613:
I think that the easiest way you'll achieve extracting numbers from the string is by using regex.
You can use Pythex to formulate your regex formula, but I believe the one that best suits your request would be this:
import re
string = "602,11 Are the numbers I would like to extract"
a = [int(i) for i in re.findall(r'\d+', string)]
a = [602, 11]
Now, Regular expressions (regex) can only be used to recognize regular languages. The language of mathematical expressions is not regular;
So, for you to extract and parse a math expression from a string you'll need to implement an actual parser in order to do this.

How can I turn a string that contains numbers and operators into a result?

I want to convert this string into a result n for the output to be 11.
a = "1+5*6/3"
print (a)
The eval() built-in function can evaluate a Python expression including any arithmetic expression. But note the eval() function is a security concern because it can evaluate any arbitrary Python expression or statement so should be used only if the input to evaluate is controlled and trusted user input. There are examples to why eval() is dangerous in this question.
a = "1+5*6/3"
result = eval(a)
print(result)
Output:
11.0
Using ast module as an alternative to eval()
A safe alternative to eval() is using ast.literal_eval. Recent Python 3 versions disallows passing simple strings to ast.literal_eval() as an argument. Now must parse the string to buld an Abstract Syntax Tree (AST) then evaluate it against a grammar. This related answer provides an example to evaluate simple arithmetic expressions safely.
You can directly use the python eval function.
a = eval("1+5*6/3")
print(a)

Expand and simplify an expression based on a string input

I have an input like "2(5x+4) + 3(2x-1)" in plain text and I need to expand and simplify it. It appears sympy requires it to be entered as a python object made up of python types. Is there a way to automatically parse it / a library that doesn't require it so I can give it the string and it gives me the answer in a human readable format?
sympy already has such a parser built-in under sympy.parsing.sympy_parser.parse_expr. To get the results you want with your input statement you also have to add the implicit_multiplication transformation (since sympy otherwise won't generate statements that make sense for 2( and 5x):
from sympy.parsing.sympy_parser import (
parse_expr,
standard_transformations,
implicit_multiplication,
)
parse_expr("2(5x+4) + 3(2x-1)", transformations=standard_transformations + (implicit_multiplication,))
You want to use sympify function, for your expression it's gonna be like this:
sympify('2*(5*x+4) + 3*(2*x-1)')

How to evaluate a mathematical expression string the user passed to the program in python?

I wanted to write a program where the user can pass in the mathematical expression that they want to evaluate as a string.
So for instance, if the user enters a formula and other necessary arguments as string
sin(x**2)/x, 0, pi/2
and I want to process that as an integral with the help from math of sympy, how shall I do it? I know how the package sympy can process mathematical expressions, but I don't know how to do it when the expression is a string.
Thanks for the help!
You probably want the sympify function.
You can also use the split() function to split the string the user types into an array, in order to get the other necessary arguments you mention needing.
For example:
from sympy import sympify
def evaluate(x, args[]):
# do stuff
return answer
in = input("Enter your expression: ")
x = in.split(",")
print(evaluate(x[0], [x[1], x[2], ...]))
EDIT: Just realized I forgot to describe how to use sympify, which is probably the most important thing with this question. Here is a simple example that should get across how to use it:
x = sympify("x**2")

How to use not logical operation in python

inputing an logical expression as string and evaluating, i'm getting proper output
str1 = "(1|0)&(1|1&(0|1))"
print eval(str1)
o/p: 1
But the same way if i'm including not operator as ~, the output goes wrong.
str1 = "(~0|~1)&(~1|0)"
print eval(str1)
o/p: -2
Is there any other way of representing not operator here to get proper answer.
These are not logical expressions but bitwise expressions. That is the reason why ~0 == -1. Instead you can look for a parser that parses these expressions the way you want. A quick google search showed up this stackoverflow question.
Sympy seems to implement a similar thing: sympy logic
The logic module for SymPy allows to form and manipulate logic expressions using symbolic and boolean values
&, | and ~ are bitwise operators.
For logic operators use and, or and not.
If your intention is to do logical operations, prefer to use the appropriate boolean values:
True / False
str1 = "(not 0|not 1) and (not 1|0)"
print eval(str1)
In python NOT is not
Ref : https://docs.python.org/2/library/stdtypes.html

Categories