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
  • 398,270
  • 210
  • 566
  • 880
George Burrows
  • 3,391
  • 9
  • 31
  • 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
  • 85,954
  • 40
  • 175
  • 219