how to you evaluate a string and the words that you can't evaluate keep the same?

string = input() string = (''.join([str(eval(s)) if ('(' in s and ')' in s) else s for s in string.split(' ')])) print(string) 

with this code there are some problems:

  1. if I write 5-(2-sp.sqrt(4)) it will give me an EOF error because it will split the words in a way that sp.sqrt(4) will be sp.sqrt(4)). It should be sp.sqrt(4)

  2. if i write ‘2-10’ it won’t evaluate it and will just return ‘2-10’; it should return ‘-8’. While if I write ‘2-10*(2-5)’ it will return the write answer.

  3. instead of just don’t evaluate the part that the code doesn’t recognize, it will give me an error saying that the part not recognized isn’t defined. (ex. ‘2+x-10-(5*10)’ —- name ‘x’ is not defined. It should return: ‘x-58’

Add Comment
1 Answer(s)

Issue – 1:

it will give me an EOF error because it will split the words in a way that sp.sqrt(4) will be sp.sqrt(4))

  • No, it doesn’t split the string that way because you are splitting the string using ‘ ‘, so the output for the split function will be ['5-(2-sp.sqrt(4))']
  • It won’t give an error unless and until your input has a valid python expression (in this case, I suspect the issue is with sp)

Issue – 2:

if I write ‘2-10’ it won’t evaluate it and will just return ‘2-10’ but when I write ‘2-10*(2-5)’ it will return the write answer.

It is because you have called the eval() function only if there are both ‘(‘ and ‘)’

Issue – 3:

It is because eval() takes only valid python expressions ( you can’t put an un-declared variable directly inside the parameter). In your case x was not declared before.

Solution:

There is a sympy function parse_expr which probably does what you want here:

In [20]: from sympy import parse_expr  In [21]: parse_expr('5-(2-sqrt(4))') Out[21]: 5  In [22]: parse_expr('2-10') Out[22]: -8  In [23]: parse_expr('2+x-10-(5*10)') Out[23]: x - 58 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.