aboutsummaryrefslogtreecommitdiff
path: root/challenge-034/paulo-custodio/python/ch-2.py
blob: 87134c16dcd59447592c6552500a4385c87ebfd8 (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
44
45
#!/usr/bin/python3

# Challenge 034
#
# Task #2
# Contributed by Dave Cross
# Write a program that demonstrates a dispatch table.

import sys

# simple rpn calculator
stack = []
def add():
    b = stack.pop()
    a = stack.pop()
    stack.append(a+b)

def sub():
    b = stack.pop()
    a = stack.pop()
    stack.append(a-b)

def mul():
    b = stack.pop()
    a = stack.pop()
    stack.append(a*b)

def div():
    b = stack.pop()
    a = stack.pop()
    stack.append(a/b)

def prt():
    print(stack.pop())

dispatch = {'+': add, '-':sub, '*':mul, '/':div, '.':prt}

prog = "".join(sys.argv[1:])
for c in prog:
    if c.isspace():
        pass
    elif c.isdigit():
        stack.append(int(c))
    else:
        dispatch[c]()