1

I have to perform a certain arithmetic operation between decimal numbers. The operations can be 'add', 'subtract' or 'multiply', and the desired operation will be passed in to our function along with the numbers. The way I want to do this is that I want to store the ASCII values of the operations '+', '-' and '*' and then somehow use that to perform the operation between the two numbers.

def (a, b, op):
  dict{'add':ord('+'), 'subtract':ord('-'), 'multiply':ord('*')}
  return a dict[op] b # this statement does not work

Is there a way to achieve something like that in python ?

I know one alternative is to use:

from operator import add,sub,mul

and then use the imported values in the hash instead, but for this question I am interested in finding out if its possible to do it the way I asked in the original question. Thanks !

2 Answers 2

1

Yes there is an eval() function in python which takes string as input and returns the output , so you slightly need to change the approach, eval() is generally used as :

print eval("2 + 3")
>>> 5

So the new code looks something like :

def evaluate(a, b, op):
    dict = {'add':'+', 'subtract':'-', 'multiply':'*'}
    return eval(str(a)+ dict[op] +str(b))

print evaluate(2,3,"add")
>>> 5
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah I know, But it is the demand of the question , better way would be to use a switch case or some other neat approach but I didn't want to change the intent of the question so made minimal changes to make it work , thanks for the insight, appreciated :)
1

No, this

a dict[op] b

is not valid Python.

Use the functions from operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.