0

I am having a problem.

def f(x):
    function = input("Enter yoru Function: ")
    return function


a = -1
b = 2
a_Applied = f(a)
b_Applied = f(b)

if a_Applied < 0 and b_Applied > 0:
    print "IVT Applies."
elif a_Applied > 0 and b_Applied < 0:
    print "IVT Applies"
else:
    print "IVT Does Not Apply"

This is my current code. I am trying to let the user make a function in line 2. However this breaks the program because it is a string. How do I get it to not be a string, and instead for it to be able to take a function.

Ex.

User inputs "2*x + 1" In a perfect world the program then runs 2(a) +1 and 2(b) + 1 and then compares them using the if statement. Because the input is a string ti doesn't work.

Any help?

  • Possible duplicate of [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – Sylogista May 27 '17 at 01:21
  • I don't think it is a duplicate because this one asks for a parameter-ized function instead of evaluation of a math expression. – EyuelDK May 27 '17 at 01:24

2 Answers2

1

Use lambda expression and eval function. Like this.

def read_user_function():
    function_str = input("Enter your Function: ")
    return lambda x: eval(function_str, { 'x' : x })

Call user function by

f = read_user_function()
print(f(2))

Here is a demo https://repl.it/ITuU/2.

Explanation

The function above, read_user_function returns a lambda expression, basically a function, that will evaluate the user's input with the variable, sort of like a parameter, x set to the x value that is passed to the lambda expression. This can get confusing if your new to this sort of thing but just think of read_user_function as returning an anonymous function that accepts a single argument and its body equals eval(function_str, { 'x' : x })

Warning

This is a quick and dirty solution to evaluating mathematical expression. The function would execute any valid python code and not only mathematical expression. This may be dangerous if your application is sensitive - you wouldn't want the user executing custom code.

EyuelDK
  • 3,029
  • 2
  • 19
  • 27
  • Hi EyuelIDK. Thank you so much for the answer! I do have another problem with this, and maybe you can help me out. Firstly, could you please explain what your answer does? Secondly, when I run the program with this code it does not prompt the user for a function. Thank you! – Tyler Darrow May 27 '17 at 01:30
  • EDIT: Just saw your new edits, however when I do this and put in an example function of "2x" I get this error:`Traceback (most recent call last): File "C:/Users/Will/PycharmProjects/IVT Calculator/IVT Calculator.py", line 5, in f = read_user_function() File "C:/Users/Will/PycharmProjects/IVT Calculator/IVT Calculator.py", line 2, in read_user_function function_str = input("Enter your Function: ") File "", line 1 2x ^ SyntaxError: unexpected EOF while parsing` – Tyler Darrow May 27 '17 at 01:35
  • It expects a python expression. Note that this is not the best solution, it is just a quick solution because the the function will evaluate any valid python code. – EyuelDK May 27 '17 at 01:39
  • Even with 2 * x, x is not defined is the error. I attempted to define x before running the function however it returns this error: TypeError: eval() arg 1 must be a string or code object – Tyler Darrow May 27 '17 at 01:43
  • I've put a demo up, you can run it and see. It works for me. – EyuelDK May 27 '17 at 01:46
  • That's so weird! It's telling me x is not defined when i run it. EDIT: Found the problem - I'm using python 2.7 – Tyler Darrow May 27 '17 at 01:54
0

What you're asking to do is very hard (in general). You'd need to define rigorous semantics for all your supported operations (for example, is power ^ or is it ** like you'd do in python?).

The sympy library has a start on this for you. If you assume your input is a polynomial, for example:

import sympy    
y = sympy.Poly("x^2 + 2*x + 1") 
print(y(3))
# outputs 16

sympy also has the advantage that it will accept "python-like" input as well:

import sympy
y = sympy.Poly("x**2 + 2*x + 1")
print(y(3))

Note that sympy is not limited to polynomials, just included them here as an example because polynomials are relatively simple.

Matt Messersmith
  • 12,939
  • 6
  • 51
  • 52
  • Hi mwm - I have installed sympy and have put `import sympy` at the top of my code, however PYCharm will not detect it. Do you know the fix? – Tyler Darrow May 27 '17 at 01:41
  • How did you install it? `pip install sympy`? That should put it in the right spot for Pycharm to pick it up. If you're using something like Anaconda, you need to adjust your project's interpreter to point to Anaconda. – Matt Messersmith May 27 '17 at 01:45
  • I'm using Windows, not Linux. Haha. – Tyler Darrow May 27 '17 at 01:52
  • You can `pip install` on windows (cmd or powershell, for example). I'm on windows too... – Matt Messersmith May 27 '17 at 01:53
  • Start -> type "cmd" -> prompt opens -> execute "pip install sympy" in shell. Hopefully that does the trick. Installing without `pip` can be error prone. – Matt Messersmith May 27 '17 at 14:32