I am making a simple project for my math class in which I want to verify if a given function body (string) only contains the allowed expressions (digits, basic trigonometry, +, -, *, /).
I am using regular expressions with the
My current code:
import re def valid_expression(exp) -> bool: # remove white spaces exp = exp.replace(" ", "") # characters to search for chars = r"(cos)|(sin)|(tan)|[d+/*x)(-]" z = re.findall(chars, exp) return "".join(z) == exp
However, when I test this any expression the
re.findall(chars, exp) will return a list of tuples with 3 empty strings:
('', '', '') for every character in the string unless there is a trig function in which case it will return a tuple with the trig function and two empty strings.
Ex: cos(x) ->
[('cos', '', ''), ('', '', ''), ('', '', ''), ('', '', '')]
Thank you for any explanation and/or fix.