Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a string equation to an integer answer

Tags:

python

If I have a string

equation = "1+2+3+4"

How do I change it into an int and equate the answer? I was thinking something like this but it would give an error.

answer = (int)equation
print(answer)

The equation could contain +-*/

like image 834
Michael Avatar asked Nov 13 '13 16:11

Michael


People also ask

How can a string be converted to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.

How do you convert a string to an integer in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

How do I convert a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.


2 Answers

If you are prepared to accept the risks, namely that you may be letting hostile users run whatever they like on your machine, you could use eval():

>>> equation = "1+2+3+4"
>>> eval(equation)
10

If your code will only ever accept input that you control, then this is the quickest and simplest solution. If you need to allow general input from users other than you, then you'd need to look for a more restrictive expression evaluator.

Update

Thanks to @roippi for pulling me up and pointing out that the code above executes in the environment of the calling code. So the expression would be evaluated with local and global variables available. Suppress that like so:

eval(equation, {'__builtins__': None})

This doesn't make the use of eval() secure. It just gives it a clean, empty environment in which to operate. A hostile user could still hose your system.

like image 121
David Heffernan Avatar answered Oct 03 '22 18:10

David Heffernan


This works if you only have digits and plusses:

answer = sum(float(i) for i in equation.split('+'))

or if you know they will only be integers

answer = sum(int(i) for i in equation.split('+'))

If you want to be able to evaluate more than that, I suggest you do your homework:

  • Look up the string module (which has string.digits)

  • the math module, which has your operations

  • create logic to perform the operations in proper order

Good luck!

like image 32
Russia Must Remove Putin Avatar answered Oct 03 '22 20:10

Russia Must Remove Putin