Write your own calculator one, function analysis
The user enters a similar expression like this (4+ 50)-((100 + 40) *5/2-3*2* 2/4+9) * ((((3 + 4)-4)-4), assuming that the expression contains no special symbols except spaces, ' + ', '-', ' * ', '/', and parentheses, and then straight Then write the code to parse the expression, achieve subtraction , The final result and the actual computer calculated results must be consistent.
Second, the required knowledge points
- Processing of strings
- The use of regular expressions
- function recursion
Three, the procedure realization process analysis
- Processing user-entered strings, removing extra spaces
- Processing strings with regular expressions, extracting numbers and operators from them, and converting them into lists
- Write a function that handles the basic expression of basic operations without parentheses
- Write a function that recursively handles parentheses, computes the expression in the inner parenthesis, and then replaces the inner parentheses with the computed result, at the end of the recursive outer layer, and returns the desired result.
Iv. Concrete implementation Process 1. Handling user Input
Processing user input is simple, here we just need to remove the extra space, the implementation code is as follows:
Implement a simple calculator with Python