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)')
Related
I'm using MathJax to render math equations on my website. I use Python to create those math equations and I use f-strings a lot.
Currently, I have to concatenate every string because to write a square root in mathJax (as far as I can tell), you can only use sqrt{x=3}, but that's a problem because in Python f-strings use {} too.
Is there any other way to write a square root in mathJax or fraction in mathJax without using curly brackets?
An example of what I'm talking about/in other words:
Off of what I know currently, this is how you write a square root in mathJax:
$$sqrt{4}$$
But in Python when dealing with f-strings:
x = 4
equation = f'$$sqrt{x}$$'
creates
$$sqrt4$$
– which is not what I want.
Of course I see that you can just concatenate the string by doing and not do an f-string:
equation = '$$sqrt{' + x + '}$$'
However when I'm doing larger problems, and I'm making a lot of varying equations and this takes forever to do for every string.
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")
I want to convert a string to a Python statement.
Taking string input from a text file e.g. 'dataframe['Column_name'].sum()'
Executing the string as a Python statement e.g. dataframe['Column_name'].sum()
Storing the result in some variable
It's possible to do this, but not recommended. You do not have any control over what the string contains if it comes from the user. There is probably a better way to achieve what you really want.
If you really, absolutely, unavoidably have to, you can use eval:
x = eval('dataframe["Column_name"].sum()')
But it is probably easier to only take, for example, the column name from the user and use that in a function call:
column_name = "Column_name" # or read it from the file
x = dataframe[column_name].sum()
#previous code
with open("file.txt","r") as f:
x = eval(f.readline())
#the rest of the code, using x however you want
I wouldn't do it if other users are supposed to be able to use the script however they want. If this is for learning purposes of for your own use, it's up to you.
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.
I'm trying to trim a sub-string from the beginning of a string based on a condition:
For instance, if the input is a domain name prefixed with http, https and/or www, it needs to strip these and return only the domain.
Here's what I have so far:
if my_domain.startswith("http://"):
my_domain = my_domain[7:]
elif my_domain.startswith("https://"):
my_domain = my_domain[8:]
if my_domain.startswith("www."):
my_domain = my_domain[4:]
print my_domain
I've tried to use these inbuilt functions (.startswith) instead of trying to use regex.
While the code above works, I'm wondering if there is a more efficient way to combine the conditions to make the code shorter or have multiple checks in the same conditional statement?
I know regex is computationally slower than a lot of the built in methods but it is a lot easier to write code wise :)
import re
re.sub("http[s]*://|www\." , "", my_domain)
edit:
As mentioned by #Dunes a more correct way of answering this problem is.
re.sub(r"^https?://(www\.)?" , "" , my_domain)
Old answer left for reference so that Dunes comment still has some context.
Use urllib.parse (Python 3).
>>> from urllib import parse
>>> components = parse.urlsplit('http://stackoverflow.com/questions/38187220/stripping-multiple-characters-from-the-start-of-a-string')
>>> components[1]
'stackoverflow.com'
The Python 2.7 equivalent is named urlparse.
To cover the 'www.' case, you could simply do
* subdomains, domain, ending = components[1].split('.')
return '.'.join((domain, ending))
In Python 2.7 you don’t have access to * unpacking but you can use a list slice instead to get the same effect.