Python algorithm design source code: https://github.com/MakerChen66/Python3Algorithm
Copyright statement: Originality is not easy, this article prohibits plagiarism, reprinting, infringement must be investigated!
Table of contents
1. Suffix expression
Although people primarily use the infix expression notation in algebraic expressions, postfix expressions (also called reverse Polish expressions) are easier to parse algorithmically.
Infix expressions: Binary operators are always placed between the two operands associated with them, such as 5 + 2, 9 * 4
Postfix expressions: Binary operators are placed after their operands, such as 5 2 + , 9 4 *
For example, the following expressions are equivalent, the first is an infix expression and the second is a postfix expression.
2 * (1 + 3) = 2 1 3 + *
When you are implementing your first expression parser, postfix and prefix notation is the best way to go. Corresponding to the stack is: push into the stack (append()), pop out of the stack (pop())...
Python algorithm implementation:
math = {
'+': float.__add__,
'-': float.__sub__,
'*': float.__mul__,
'/': float.__truediv__,
'^': float.__pow__,
}
def postfix(expression):
stack = []
for x in expression.split():
if x in math:
x = math[x](stack.pop(-2), stack.pop(-1))
else:
x = float(x)
stack.append(x)
print(stack.pop())
postfix('1 2 + 4 3 - + 10 5 / *') # 相当于计算 ((1+2)+(4-3))*(10/5)
Note: stack.append() means push into the stack, stack.pop() means pop out of the stack, and split() means split
Output result:
As shown in the figure, the operation result is 8, and the result is correct
2. Source code download
Python algorithm design source code download:
- GitHub download link: Portal
- Link to the original text: Read the original text
3. Author Info
Author: Xiaohong's Fishing Daily, Goal: Make programming more interesting!
Original WeChat public account: " Xiaohong Xingkong Technology ", focusing on algorithms, crawlers, websites, game development, data analysis, natural language processing, AI, etc., looking forward to your attention, let us grow and code together!
Copyright Note: This article prohibits plagiarism and reprinting, and infringement must be investigated!