1

I'm writing a program that involves calculating the maximum of a user defined function, however if the user enters a function in terms of a variable such as x, i.e.

input = x**2 + 2*x + 1

I (fairly expectedly) get an error as x is not defined.

Does anyone know of an effective way to allow a user to input a function in terms of a single variable such as x?

Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861
George Burrows
  • 3,281
  • 9
  • 30
  • 31

1 Answers1

2

If you are not worried about security much, simplest solution is to eval the expression e.g.

def calculate(value, function):
    x = value
    return eval(function)

print calculate(2, "x**2 + 2*x + 1")
print calculate(2, "x**3 - x**2 + 1")

output:

9
5

You can make it more secure by passing an empty builtin dict but still I think some clever code will be able to access internals of your code.

Anurag Uniyal
  • 81,711
  • 39
  • 167
  • 215