Transform string into operator

0

I have the following string '1 + 1', I have to transform the numbers into integers and perform the operation, you have to transform the string '+' into the + operator, or other operators like the '*' operation using if's, however how many operators wanted to make a leaner code.

    
asked by anonymous 22.09.2017 / 19:58

2 answers

1

To do "right" is something that depends on how much functionality you want, and it is something that, if you want to read parentheses, can be very complicated.

But to keep it simple, let's assume that the input expressions are always in the form number, operator, number, and everything separated by spaces - and also let Python itself process numeric operands to give its value as a number floating. (that is, let's call the built-in "float" instead of processing the digit-by-digit input to construct the operands)

So we focus only on the operator itself - and we can create a simple dictionary that maps the operator's symbol to a function that receives two parameters. To get shorter still, we can use the keyword lambda that allows the definition of simple functions as expressions, within the dictionary body itself.

Then you can do something like this:

operadores = {
  "+": lambda op1, op2: op1 + op2,
  "-": lambda op1, op2: op1 - op2,
  "*": lambda op1, op2: op1 * op2,
  "/": lambda op1, op2: op1 / op2
}

def process(expression):
   op1, operator, op2 =expression.split()
   op1 = float(op1)
   op2 = float(op2)
   return operadores[operator](op1, op2)
    
23.09.2017 / 20:01
1

I'm assuming that your input string always has the format " N operator N " where N is the number in the string. If it is N operator M the solution will not work.

link

import operator
def tamanho_do_numero(valor):
 tamanho = (len(valor)-1)//2 #tamanho de N. Importante para o slice
 return tamanho

valortotal = "111+111"
tamanhoN = tamanho_do_numero(valortotal)
calculo = { "+": operator.add, "-": operator.sub,"*": operator.mul,"/":operator.truediv}#etc
valorN=int((valortotal[:tamanhoN]))
operador = (valortotal[tamanhoN])

print (calculo[operador](valorN,valorN))
    
24.09.2017 / 18:50