In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use stack to achieve simple calculator in Python". In daily operation, I believe that many people have doubts about how to use stack to achieve simple calculator in Python. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubt of "how to use stack to achieve simple calculator in Python". Next, please follow the editor to study!
Main idea: read-parse-print-loop.
The read phase refers to reading the string entered by the user after the prompt (cal >).
The parse phase includes splitting the string entered by the user into a single object such as the symbol +, or the number 1.2. Secondly, the infix expression is converted into the suffix expression, and then the value of the suffix expression is calculated.
The print phase refers to printing the values of the parse phase on the terminal.
The loop phase refers to repeating the above unless the user enters the exit symbol or Ctrl + C terminates the program.
Realize the effect picture:
Stack
In order to implement the suffix and suffix expressions, we need to use the data structure of stack.
Stack is a first-in-first-out data structure. When a function is called, it will use the stack to save the address and other information of the current program. The previous depth-first search is based on the stack.
I wrote an article about the use of stack. Here is a brief description of the use of stack:
The push function adds elements at the top of the stack, the pop function deletes the elements at the top of the stack, and the top function looks at the top elements of the stack.
Class Stack: def push (self, value: t)-> None: pass def pop (self)-> T: pass def top (self)-> T: pass
Word segmentation
Participle is an important part of the parse stage.
We define the symbol +-* / ().
Replace these symbols in these strings with: spaces + symbols + spaces
+ = > spaces + spaces
Divide the string into spaces to get the final participle
After the above operation, the word segmentation function of positive numbers and operators can be realized.
# Python efficient programming def tokenize (expression: str)-> Generator [str, None, None]: for symbol in symbols: # replacement string expression = expression.replace (symbol, f "{symbol}") # Segmentation string seq: List [str] = expression.split ()
In order to realize the word segmentation of negative numbers, we need to iterate the word segmentation sequence and convert the'- 'and the following numbers into a whole. We have two cases in which-is treated as a negative sign, in the first case, the negative sign is at the beginning of the string, and in the second case, the sign before the negative sign is the left parenthesis.
# Python efficient programming for I, item in enumerate (expression.split ()): if item = = "-": # the current symbol is set to "# the next symbol is set to negative if I-1
< 0 or seq[i - 1] == "(": seq[i] = "" seq[i + 1] = f"-{seq[i + 1]}" # 若字符串不为空,打印字符串 if seq[i]: yield seq[i] 中缀表达式 中缀表达式就是我们写的各种表达式,如 3 + 2 * 4。我们希望将其转化为后缀表达式,示例如下: 中缀表达式 ==>1 + 5 * 4 + (3 * 2 + 4) * 6 suffix expression = > 15 4 * + 3 2 * 4 + 6 * +
We need to prepare a stack stack for temporary storage of operators and a sequence seq for holding the output, that is, suffix expressions.
Conversion rules:
Iterate the word segmentation sequence, encounter a number, and output the number to the sequence seq.
Define each symbol priority, where multiplication and division > addition and subtraction > closing parenthesis. Compare the priority of the current symbol with the top element of the stack, if the priority of the current element is less than or equal to the priority of the top element of the stack, pop up the top element of the stack, output it to the seq sequence, and then press the current element into the stack. If the priority of the current element is higher than that of the element at the top of the stack, or if the current element is a closing parenthesis, we press the current element directly into the stack.
If we encounter the left parenthesis, we pop up the elements in the stack and output them to the seq sequence. Where the left and right parentheses are not output to the sequence.
Finally, the remaining symbols in the stack are output to the seq sequence.
# Python efficient programming # iterative 1 + 5 * 4 + (3 * 2 + 4) * read into 1 and output to seq, + stack # read into 5 and output to seq stack = = > + seq = = > 1 "read *, * priority > + priority # push * into the stack, read into 4 and output stack = > + * seq = > 15" read in +, + priority
< * 优先级# 将 * 输出到 seq 序列中# + 优先级 +seq ==>1 54 * + # read (, press into the stack, read 3, press into the stack stack = = > + (seq = > 154 * + read in *, press into the stack, read 2, press into the stack stack = = > + (* seq = = > 154 * + 3 "read in +, * output, + push into the stack, 4 output stack = > + (+ seq = > 154 * + 32 * read), + output Pop up (stack = > + seq = = > 1 54 * + 32 * 4 + # read *, press into the stack, 6 output stack = = > + * seq = = > 1 54 * + 3 2 * 4 + 6 * +) output the remaining symbols in the stack stack = = > seq = > 1 54 * + 3 2 * 4 + 6 * +
The code is as follows:
# Python efficient programming def parse_infix (expression: str)-> List [str]: stack: Stack [str] = Stack () result: List [str] = [] for expr in tokenize (expression): if not is_float (expr) and expr not in symbols: raise SymbolError () if is_float (expr): result.append (expr) elif expr = ")": while stack.top! = "(": result.append (stack.pop ()) stack.pop () elif expr = "() Stack.push (expr) elif stack.top and compare_priority (expr Stack.top): result.append (stack.pop ()) while stack.top and compare_priority (expr, stack.top): result.append (stack.pop ()) stack.push (expr) else: stack.push (expr) while stack: result.append (stack.pop ()) return result
Suffix expression
The rule of suffix expression: press the stack when you encounter a numerical value; when you encounter a symbol, two elements are popped out of the stack, the operation results of the two elements are calculated, and the resulting results are pushed into the stack.
# Python efficient programming def parse_sufix (expression: List [str])-> float: stack: Stack [str] = Stack () result: float = 0.0 for expr in expression: if is_float (expr): stack.push (expr) else: elem1: str = stack.pop () elem2: str = stack.pop () result = evaluate (expr, float (elem2), float (elem1) stack.push (str (result)) if stack: result = result (result ()) The study on "how to use stack to achieve a simple calculator in Python" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.