Turn string into operator

Asked

Viewed 920 times

0

I have the following string '1+1', I have to transform the numbers into integers and perform the operation, have to transform the string '+' into the operator +, or other operators like '*' made a first draft of the operation using if’s, but as there are several operators wanted to make a more streamlined code.

2 answers

1


doing "right" is something that depends on how much functionality you want, and it’s something that, if you want to read parentheses for example, can get really complicated.

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

So we just focus on the operator itself - and we can create a simple dictionary that maps the operator symbol to a function that takes two parameters. To get even shorter, we can use the keyword lambda which 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)

1

I am assuming that your input string always has the format "NoperatorN" where N is the number present in the string. If NoperatorM the solution will not work.

https://docs.python.org/3/library/operator.html

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))

Browser other questions tagged

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