Question

Input:

1st integer given: 3, 
2nd integer given: 2, 
Primitives given in a STRING: '+'

Expected output:

5

Since 3+2=5

My approach:

str(3)+ '+' + str(2)  --> '3+2'
int('3+2') --> Wishfully thinking: 5

As expected, I will get ValueError: invalid literal for int() with base 10: '3+2'.

Any idea how can I approach this? I must use all the input given, meaning I must use the primitives in the string ('+')

Thanks!!

Was it helpful?

Solution

Use eval:

first = raw_input('1st integer given: ')
second = raw_input('2nd integer given: ')
primitives = raw_input('Primitives given in a STRING: ')

equation = first+primitives+second
answer = eval(equation)
print answer

Runs as:

1st integer given: 3
2nd integer given: 2
Primitives given in a STRING: +
5

Or:

1st integer given: 99
2nd integer given: 9
Primitives given in a STRING: /
11

OTHER TIPS

You can use eval.

eval( str(2) + '+' + str(3) )

You can even use this

print( eval( input( "insert equation: " )))

Or if you want to separate the values:

inp = input("num1 num2 operation: ")
num1, num2, operation = inp.split()
print( eval ( str(num1) + str(operation) + str(num2) ))

This function recursively calls itself breaking down its components one at a time. It also follows standard Order of operations.

def evaluate(str_func):
    if "-" in str_func:
        return evaluate(str_func[:str_func.index("-")].strip()) - evaluate(str_func[str_func.index("-")+1:].strip())
    if "+" in str_func:
        return evaluate(str_func[:str_func.index("+")].strip()) + evaluate(str_func[str_func.index("+")+1:].strip())
    if "*" in str_func:
        return evaluate(str_func[:str_func.index("*")].strip()) * evaluate(str_func[str_func.index("*")+1:].strip())
    if "/" in str_func:
        return evaluate(str_func[:str_func.index("/")].strip()) / evaluate(str_func[str_func.index("/")+1:].strip())
    return float(str_func.strip())

>>> evaluate("3 + 5")
8.0
>>> evaluate("3 + 5 / 2")
5.5
>>> evaluate("1 * 2 / 3 + 4 - 5")
-0.33333333333333304
>>> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top