How to store an operator?

2

I'd like to know if you have any way to save an operator to a variable, for example

a = <

if 5 a 5:
    pass
    
asked by anonymous 12.02.2018 / 02:29

2 answers

6

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 at Repl.it | Ideone

From this, you can mount a map that relates the text with the operator and its library function.

For example, with the code snippet below you can enter any of the four basic operations to be performed on 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 at Repl.it

    
12.02.2018 / 02:37
1

Alternatively you could use lambdas for this. The idea would be to basically implement the operators library as @AndersonCarlosWoss mentioned in your answer .

The advantage of using lambdas would be to allow generalized binary operators. The downside is that the library implementation of the operators it provides is probably much better than yours.

# 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))
    
12.02.2018 / 17:45