aboutsummaryrefslogtreecommitdiff
path: root/challenge-039/paulo-custodio/python/ch-2.py
blob: 50dd9643463f6fb6cfbd016c8e9f2b11038f9efb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python3

# Challenge 039
#
# TASK #2
# Contributed by Andrezgz
# Write a script to demonstrate Reverse Polish notation(RPN). Checkout the wiki
# page for more information about RPN.

import sys

# simple rpn calculator
stack = []

def rpn(op):
    if op.isdigit():
        stack.append(int(op))
    elif op == '+':
        b = stack.pop()
        a = stack.pop()
        stack.append(a+b)
    elif op == '-':
        b = stack.pop()
        a = stack.pop()
        stack.append(a-b)
    elif op == '*':
        b = stack.pop()
        a = stack.pop()
        stack.append(a*b)
    elif op == '/':
        b = stack.pop()
        a = stack.pop()
        stack.append(a/b)
    elif op == '.':
        a = stack.pop()
        print(a)
    elif op.isspace():
        pass
    else:
        print("invalid operation:", op)

for c in "".join(sys.argv[1:]):
    rpn(c)