1

I need help with returning the value of expression(expression being the parameter of the function).

This is what i have tried so far. It's just an example with a random equation, my plan would be to understand how to solve it correctly so i could later on tranform it into a function

sum = 0
eq = '2+4-5'
string = ""
for x in eq:
    if x in ('+', '-'):
        if x == '+':
            sum += int(string)
        elif x == "-":
            sum -= int(string)
        string = ""
    else:
        string += x
sum += int(string)
print(sum)
"1+2" => 3   # input  =  "1+2" and the output of the function would be 3
"-1+21" => 20
"+1-1" => 0
  • 1
    Do you only need to support addition and subtraction? How about negative numbers (f. ex. would the following be valid: `5 + -2`)? How about parentheses and multiplication/division (which would introduce the problem of operator precedence)? – exhuma Oct 01 '19 at 14:38
  • `2+4-5` is not an equation (it's usually called an *expression*). An equation is a statement about equality, often involving one or more unknown entities, like `x = 2+4-5`. – molbdnilo Oct 01 '19 at 14:52
  • @exhuma yes, only addition and subtraction and there must be no 2 consecutive operands. –  Oct 01 '19 at 15:00
  • @molbdnilo thanks for informing me! –  Oct 01 '19 at 15:01

2 Answers2

3

Look up the eval() function:

>> eq = "2+4-5"
>> eval(eq)
1

As said in the comments eval() evaluate the string passed as Python code which is potentially dangerous.

Yujin Kim
  • 141
  • 1
  • 10
  • 4
    Using eval is very dangerous advice as it can execute any Python code. While this solution will *technically* work I would refrain from using it. This code looks like an exercise to learn coding, so it may be acceptable here. But then we wouldn't learn any coding lesson. – exhuma Oct 01 '19 at 14:36
  • @exhuma but it actually answered the initial question, imo it would be better to include security notice, but still. – marzique Oct 01 '19 at 14:41
  • 1
    I guess OP can use that to safely evaluate equations: https://stackoverflow.com/questions/43836866/safely-evaluate-simple-string-equation – Yujin Kim Oct 01 '19 at 14:42
  • @DenisTarnavsky I agree. This is why I tried to be more elaborate in the commen than just saying "eval is evil" or somesuch. We are still all here to learn something and even learning what not to do is a good step forward. – exhuma Oct 01 '19 at 14:43
  • Just FYI, [this article](https://www.geeksforgeeks.org/eval-in-python/) shows how to make `eval` calls safer. – GZ0 Oct 01 '19 at 14:54
2

Try This one:

import re
eq = '+1-1'
ls = [int(i) for i in re.findall('[-+]?[0-9]+', eq)]
res = sum(ls)
print(res)
elomat
  • 139
  • 4