This article example describes the Python implementation to handle inverse Polish expressions. Shared for your reference, as follows:
Name: Inverse Polish Expression
Foreign Name: Reverse Polish Notation
Alias: Suffix Expressions
Inverse Polish expressions are also called suffix expressions. In the usual expression, the binary operator is always placed between the two objects with which it is associated, and this representation is also known as the midfix representation. The Polish logician in 1929 proposed another way of representing expressions, according to which each operator is placed after the object of its operation, so it is called the suffix representation. This is covered in two courses, Data Structures and Compilation Principles. Its advantage is that it can take care of any ordinary expression with just two simple operations, in-stack and out-stack. The operations are as follows:
If the current character is a variable or a number, then the stack, if it is an operator, then the top two elements of the stack will be popped out for the corresponding operation, the results into the stack, and finally when the expression is scanned, the stack is the result.
Handling in Python2:
#!/usr/bin/env python2 # -*- coding: utf-8 -*- RPN_str = '1 2 + 3 4 - *' stack = [] for c in RPN_str.split(): if c in '+-*': i2 = () i1 = () print i1,c,i2 print eval('%s'*3 % (i1,c,i2)) (eval('%s'*3 % (i1,c,i2))) else: (c) print 'result', stack[0]
Arithmetic results:
1 + 2
3
3 - 4
-1
3 * -1
-3
result -3
Of course there are a few more Hacker ways to write it:
RPN_str = '1 2 + 3 4 - *'
print reduce(lambda stack, c: stack+[eval('{2}{1}{0}'.format((),c,()))] if c in '+-*' else stack+[c], RPN_str.split(),[])[0]
Arithmetic results:
-3
Readers interested in more Python related content can check out this site's topic: thePython Data Structures and Algorithms Tutorial》、《Summary of Python coding manipulation techniques》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope the description of this article will help you in Python programming.