0
import math

term = ['math.sqrt', 'math.pi', 'math.sin', 'math.cos', 'math.tan', 
'math.log', 'math.log', 'math.pow', 'math.cosh', 'math.sinh', 
'math.tanh', 'math.sqrt', 'math.pi', 'math.radians', 
'math.e','math.radians']
replace = ['√', 'π', 'sin', 'cos', 'tan', 'log', 'ln', 'pow', 'cosh', 
'sinh', 'tanh', 'sqrt', 'pi', 'radians', 'e', 'rad']

equation = input('')

for word in replace:
    equation = equation.replace(word, term[replace.index(word)])

I am trying to evaluate only the calculations in 'equation' that are also found in the 'term' and afterwards replace the values that we found in 'equation'

Ex. input: x + 5 - sqrt(4) = 9

then my program will replace sqrt(4) with math.sqrt(4)

then it should calculate math.sqrt(4); so math.sqrt(4) = 2

and lastly replace the 2 with sqrt(4) in 'equation'; so, equation = x + 5 - 2 = 9

1 Answers1

0

I can help you, but with using an eval statement, which is generally considered somewhat of bad practice

The solution, in one line, is:

' '.join([str(eval(s)) if ('(' in s and ')' in s) else s for s in equation.split(' ')])

Let's break it down:

  • equation.split(' ') splits the equation string into a list of strings separated by an empty space: ['x', '+', '5', '-', 'math.sqrt(4)', '=', '9']
  • [str(eval(s)) if ('(' in s and ')' in s) else s for s in equation.split(' ')] runs str(eval(s)) on any element of the list that satisfies the condition ('(' in s and ')' in s) (I'm assuming that you only open and close parentheses on the function itself).
  • str(eval(s)) evaluates the function as it is written, and then casts it back to string.
  • ' '.join([...]) joins the list elements, putting the spaces back in place.

The results comes out as:

'x + 5 - 2.0 = 9'

Just remember putting your spaces in the right places in the input.

Itamar Mushkin
  • 2,803
  • 2
  • 16
  • 32