Click here to Skip to main content
14,775,260 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I need to write a math expression calculator,:
" What is 2 plus 2?" should return 4. But without the priority of operations,for example " What is 7 plus 2 multiply 3?" should not return 13, but 27. so i tried eval,but it doesn't work here(( btw, i've been learning python for a short period of time, so pls, try to help me with the most simple code,you could ever imagined :D THANKS IN ADVANCE

What I have tried:

Unfortunately,nothing yet,cuz i can’t even imagine a solving for this one
Updated 22-Oct-20 21:18pm
Gerry Schmitz 22-Oct-20 17:19pm

1 solution

You should build a very simple parser:
  1. Check and discard the 'start' condition ("What is"), get the first number, assign it to current result.
  2. If you find the 'finish' condition ("?"), then you've done: report the result value.
  3. Gather the operator (e.g. "plus", "multiply",...) and second operand, apply the operation (using current value of result as first operand) and store the computed value into result.
  4. Goto point 2.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900