Try to calculate RPN in Python (for beginners)

Introduction

After solving AOJ in various ways, I touched on "Reverse Polish Notation" for the first time in a while. 0087:Strange Mathematical Expression So, after reviewing, I wrote Reverse Polish Notation (RPN) in Python.

What is Reverse Polish Notation in the first place?

When I learned it in a university class, I was only thinking, "Hey, I don't have to write parentheses one by one, and once I get used to it, it's easy to use." It seems to be compatible with computers just because you don't have to wait for all the numbers and operators you want to calculate without having to think hard.

Also, it seems to be compatible with Japanese people. For example 「(1 + 3) * (9 - 2)」 If you write the mathematical expression that you are familiar with (this is called infix notation) in reverse Polish notation 「1 3 + 9 2 - *」 It can be rewritten as. This means "Add 1 and 3, subtract 2 from 9 and multiply them." That's why the Japanese translation is done.

Writing is easy with Stack. -If the input is a numerical value, push to Stack -If the input is an operator, pop the numerical value for the argument from the Stack and calculate, and push the return value again. Just repeat this.

By the way, this is a digression, but do you know why it is called "(Reverse) Polish Notation"? I completely misunderstood that such a description method was common in Poland (eh?), But that is not the case. It is said that it is called because the logician Jan Ukasevich who originally devised this description method was Polish. If so, it might be called "Ukasevich notation", but his name Jan Łukasiewicz was roughly called "Polish notation" because it was difficult for the English people at that time to pronounce it. That's right.

It's ironic that Lisp, which has a reputation for having a lot of parentheses, uses Polish notation, which was devised to eliminate the parentheses that indicate priority.

[Wikipedia-Jan Łukasevich](https://ja.wikipedia.org/wiki/%E3%83%A4%E3%83%B3%E3%83%BB%E3%82%A6%E3%82%AB % E3% 82% B7% E3% 82% A7% E3% 83% B4% E3% 82% A3% E3% 83% 81)

Actually write in Python

rpn.py


def RPN(states):
    '''
Function to calculate Reverse Polish Notation
    '''
    operator = {
        '+': (lambda x, y: x + y),
        '-': (lambda x, y: x - y),
        '*': (lambda x, y: x * y),
        '/': (lambda x, y: float(x) / y)
    }
    stack = []
    print('RPN: %s' % states)
    for index, z  in enumerate(states):
        if index > 0:
            print(stack)
        if z not in operator.keys():
            stack.append(int(z))
            continue
        y = stack.pop()
        x = stack.pop()
        stack.append(operator[z](x,y))
        print('%s %s %s =' % (x, z, y))
    print(stack[0])
    return stack[0]

def test():
    print("OK" if RPN("37+621-*+") == 16 else "NG")

if __name__ == '__main__':
    import sys
    RPN(sys.argv[1])
    test()
$ python rpn.py 37+621-*+
RPN: 37+621-*+
[3]
[3, 7]
3 + 7 =
[10]
[10, 6]
[10, 6, 2]
[10, 6, 2, 1]
2 - 1 =
[10, 6, 1]
6 * 1 =
[10, 6]
10 + 6 =
[16]
OK

in conclusion

When I was looking at some sites after reviewing, many people used the enumerate function for implementation, so I imitated it.

>>> a = ['a','b','c']
>>> for x in a:
...     print(x)
... 
a
b
c

For a list like

>>> a = ['a','b','c']
>>> for i,x in enumerate(a):
...     print('%d : %d' % (i,x))
... 
0 : a
1 : b
2 : c

You can do something like this.

Embarrassingly, I haven't used it until today, but I found it to be very useful when I want to retrieve the index and the element at the same time (in a case like this).

Last but not least, the calculator that can calculate PRN is [Amazon List](https://www.amazon.co.jp/RPN%E8%A8%98%E6%B3%95%E3%81% It was summarized in AE% E5% 87% BA% E6% 9D% A5% E3% 82% 8Bhp% E9% 9B% BB% E5% 8D% 93 / lm / R2KBMLT0XMHPJ2).

I want ... isn't it?

Recommended Posts

Try to calculate RPN in Python (for beginners)
Try to calculate Trace in Python
Try to calculate a statistical problem in Python
~ Tips for beginners to Python ③ ~
Run unittests in Python (for beginners)
Try logging in to qiita with Python
[For beginners] Try web scraping with Python
[For beginners] How to register a library created in Python in PyPI
Memo # 4 for Python beginners to read "Detailed Python Grammar"
The fastest way for beginners to master Python
First steps to try Google CloudVision in Python
Try to implement Oni Maitsuji Miserable in python
3.14 π day, so try to output in Python
Try auto to automatically price Enums in Python 3.6
Python for super beginners Python for super beginners # Easy to get angry
Memo # 1 for Python beginners to read "Detailed Python Grammar"
python textbook for beginners
Try gRPC in Python
Memo # 2 for Python beginners to read "Detailed Python Grammar"
Try 9 slices in Python
Memo # 7 for Python beginners to read "Detailed Python Grammar"
Introduction to Programming (Python) TA Tendency for beginners
Memo # 6 for Python beginners to read "Detailed Python Grammar"
How to make Python faster for beginners [numpy]
OpenCV for Python beginners
Memo # 5 for Python beginners to read "Detailed Python Grammar"
[Introduction for beginners] Working with MySQL in Python
[For beginners] Introduction to vectorization in machine learning
Introduction to Graph Database Neo4j in Python for Beginners (for Mac OS X)
Basic story of inheritance in Python (for beginners)
Data analysis in Python Summary of sources to look at first for beginners
[Cloudian # 10] Try to generate a signed URL for object publishing in Python (boto3)
Rock-paper-scissors poi in Python for beginners (answers and explanations)
Tool to make mask image for ETC in Python
Python beginners try adding basic auth to Django admin
Try to make a Python module in C language
How to convert Python # type for Python super beginners: str
[For beginners] How to study Python3 data analysis exam
Try to improve your own intro quiz in Python
How to run python in virtual space (for MacOS)
Try searching for a million character profile in Python
[For beginners] Learn basic Python grammar for free in 5 hours!
Python # How to check type and type for super beginners
Calculate mW <-> dBm in Python
To flush stdout in Python
Learning flow for Python beginners
Try to understand Python self
Login to website in Python
Search for strings in Python
Techniques for sorting in Python
Try LINE Notify in Python
Python #function 2 for super beginners
Speech to speech in python [text to speech]
Try implementing Yubaba in Python 3
Basic Python grammar for beginners
100 Pandas knocks for Python beginners
Python for super beginners Python #functions 1
How to develop in Python
Python #list for super beginners
Introduction to Python For, While
About "for _ in range ():" in python