diff options
Diffstat (limited to 'challenge-034/paulo-custodio/python/ch-2.py')
| -rw-r--r-- | challenge-034/paulo-custodio/python/ch-2.py | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/challenge-034/paulo-custodio/python/ch-2.py b/challenge-034/paulo-custodio/python/ch-2.py new file mode 100644 index 0000000000..87134c16dc --- /dev/null +++ b/challenge-034/paulo-custodio/python/ch-2.py @@ -0,0 +1,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]() |
