0

I have a piece of code that is repeating with only a math operator changing, i.e:

x1=a+b
x2=a-b
x3=a*b
x4=a/b

is there a way to write a function that receives the operator and only applies that and thus eliminate the need to write almost the same code many times?

hopefully, something like:

def operator_modularity(op):
    return a op b

operator_modularity(+)
GalSuchetzky
  • 785
  • 5
  • 21

3 Answers3

3
def operator_modularity(op):
    return eval(f"10 {op} 10")

operator_modularity("+")
Dharman
  • 30,962
  • 25
  • 85
  • 135
takeyama
  • 31
  • 3
  • eval is evil, it allows more than i want but it's a good direction tough, maybe combining it with the dictionary solution will give a safe and modular piece of code. – GalSuchetzky Oct 26 '21 at 19:30
  • lots of fun ahead! Yep, eval is evil: use for instance `op = " in [print('you have been hacked') for x in range(1)] #"` and have fun – Pac0 Oct 26 '21 at 21:41
2

A great thing about Python is that you can keep pointers to methods. Another cool thing is the built in operators module that gives you method-call shaped references to said operators. So to do that, you could run the following:

def foo(a, b):
     operators_to_run = [operator.add, operator.sub, operator.mul]
     for op in operators_to_run:
         print(op(a,b))

There's no code repetition, and you get all the operators' results sequentially :) I hope that answers your question.

Elad Levy
  • 23
  • 1
  • 7
0

I guess you could write some code like

def all_four_operations(num1, num2):
    return (num1 + num2, num1 - num2, num1 * num2, num1 / num2)

result_array = all_four_operations(1, 7)
x1 = result_array[0] # x1 = 8
x2 = result_array[1] # x2 = -6
x3 = result_array[2] # x3 = 7
x4 = result_array[3] # x4 = 0.14
d.b
  • 32,245
  • 6
  • 36
  • 77
Jacob Glik
  • 223
  • 3
  • 10