How to store an operator?

Asked

Viewed 130 times

4

I wonder if you have any way to store an operator in a variable, for example

a = <

if 5 a 5:
    pass

2 answers

8


It has an analogous form, using the library operator. For the minor operator, there is the function lt.

from operator import lt

a = lt

if a(4, 5):
    print('4 é menor que 5')
else:
    print('4 é maior ou igual a 5')

See working on Repl.it | Ideone

From that, you can map relating the text to the operator and its function of the library.

For example, with the code snippet below it is possible to inform any of the four basic operations to be performed in operands 2 and 3.

from operator import add, truediv, mul, sub

OPERATORS = {'+': add, '-': sub, '*': mul, '/': truediv}

while True:
  operator_text = input("Qual operação realizar entre 2 e 3? [+-*/] ")
  try:
    operator = OPERATORS[operator_text]
    print('Resultado de 2 {} 3 = {}'.format(operator_text, operator(2, 3)))
  except KeyError:
    break

See working on Repl.it

If you prefer to use conditional structures, you can mount several if:

if operator == '+':
    resultado = a + b
elif operator == '-':
    resultado = a - b
elif operator == '*':
    resultado = a * b
elif operator == '/':
    resultado = a / b
...

It gets simpler for some, but I particularly dislike the repetition of code that this form presents.

Even so, none of the above solutions is perfect, as see that at no time we treat the amount of operands that each operator has. We treat all of them as binary operators (two operands), which does not include, for example, signal switching. This will not always be a problem, because it is easy to implement so that the negative sign is considered along with the operand.

4

Alternatively you could use Windows for this. The idea would be to basically implement the library operators that the @Andersoncarloswoss mentioned in his reply.

The advantage of using Leds would be to allow generalized binary operators. The downside is that the implementation in the library of the operators it provides is much more likely than its.

# para a operação de comparação
op = lambda(a, b): a < b

if op(5, 5):
  pass

# para a operação de potenciação 
op = lambda (a, b) : a**b

print(op(2, 3))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.