So, there's a fundamental difference between your user input, and your example of in-code python:
User input, in this example, will be a string literal "2*a + 3*b <=4"
You're not able to append a string literal to prob, because it's expecting a constraint or similar object -- this is where your error comes from.
prob += x
When you evaulate the same expression in python, you'll notice it lacks the quotes which I helpfully placed around the statement up there.
This is not a string literal, it's a python expression. Some part of pulp evaluates this into a constraint object, and then adds that constraint to the problem.
prob += 2*a +3*b <= 4
Now, completely ignoring the potential for arbitrary code execution, the easiest way to solve your problem is to evaluate the user input as python code and let the language do the rest:
exec("prob +="+x);
It should be noted that unless this script is entirely for your personal use, this is a terrible idea.
The correct solution from a general programming standpoint is to construct an LPConstraint object from the string, and then add your newly constructed object to prob.
In an ideal world, you'd have a constructor for LPConstraint that takes a string, or a helper method somewhere in the libraries which does this for you.
I've done (admittedly all of 5 minutes...) some reading through the documentation and can't find any such methods. Assuming nobody else turns up any luck, you're left with parsing the string yourself (and all the hassle that entails) and building a constraint object from the results.
With a problem like this the question is really one of scope:
- Where are you installing this script?
- Who is going to be using it?
- What potential damage can they do?
If you're creating the python script to run in the computer labs of a high school or university, for the love of god do not use exec.
If you're creating the python script to run on your (and possibly your friends') machine, for your own purposes, then writing a parser is a blatant waste of your time and effort -- you are not going to execute malicious code on your own box.
j="a" for i in constraints: i = i + " , \"" + j + "\"" print i k = eval(i) prob += k j += "a"prob takes a tuple of a python expression and a unique string.