Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

Python: How can I assign string representations of operators to mathematical operators using a dictionary?

My aim is to create a UDF that does simple arithmetic. I want the function to take 2 values, and then a string representation of an operator, for example 'mulitiply' and perform the operator on x to y. This is my first time attempting this, excuse the mess.

def_myArithmetic(x, y, op):
     op={'multiply': *, 'divide': /, 'add': +, 'subtract':-}
     **some loop**
         **return calculation**

what I have managed so far

import operator
def do_arithmetic(x, y, op):
  op={'multiply': operator.multiply,'divide': operator.divide,'add': operator.add ,'subtract': operator.subtract}
  for i in range(x,y):
     print (x, y)

using this bloc of code returns an error when calling the function.

Im aware this dictionary does not work. And i believe its to do with having multiple keys within one reference ?

I believe im somewhere near the right lines but clearly have no idea how to write this. It would be very helpful to have something to reference when I try to implement the rules of my choosing.

Thank you for your feedback


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your dictionary variable is replacing the op parameter. Use a different name for this.

You need to use the string argument as a key to access the corresponding dictionary element.

You need to call the operator function, not just put it in a tuple with the arguments.

There's no reason for the for loop.

There's no operator.multiply, it's operator.mul. Find the full list here.

def do_arithmetic(x, y, op):
    operations = {
        'multiply': operator.mul,
        'divide': operator.truediv,
        'add': operator.add,
        'subtract': operator.sub
    }
    return operations[op](x, y)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...