Skip to content

Instantly share code, notes, and snippets.

@wilfreddv
Created December 28, 2021 12:11
Show Gist options
  • Save wilfreddv/d5aba8ea075fb71ab8fdfe2edb093b72 to your computer and use it in GitHub Desktop.
Save wilfreddv/d5aba8ea075fb71ab8fdfe2edb093b72 to your computer and use it in GitHub Desktop.
RPN Calculator

rpn-calculator

Calculator for equations in the Reversed Polish Notation

Usage

$ ./main.py
//Your calculation goes here
//The output will be printed here

You can also use input and/or output files:

$ ./main.py < inputfile > outputfile
$ ./main.py < inputfile
$ ./main.py > outputfile
import sys
from stack import Stack
import math
"BINARY OPERATORS"
def add(a, b):
return (b + a)
def sub(a, b):
return (b - a)
def mul(a, b):
return (b * a)
def div(a, b):
if a == 0:
return 1
return (b / a)
def mod(a, b):
return (b % a)
def power(a, b):
return b ** a
"UNARY OPERATORS"
def unot(a):
return float(not(a))
def fact(a):
return math.factorial(a)
def dec(a):
return (a - 1)
def inc(a):
return (a + 1)
def root(a):
return math.sqrt(a)
def square(a):
return a ** 2
def log(a):
return math.log10(a)
def uabs(a):
return math.fabs(a)
def ln(a):
return math.log(a)
binary_ops = {
'+' : add,
'-' : sub,
'*' : mul,
'/' : div,
'%' : mod,
'^' : power
}
unary_ops = {
'n' : unot,
'!' : fact,
'--' : dec,
'++' : inc,
'r' : root,
's' : square,
'l' : log,
'a' : uabs,
'ln' : ln
}
constants = {
'pi': math.pi,
'e' : math.e
}
def calculate(line):
tokens = line.split()
stack = Stack()
for token in tokens:
if token in binary_ops:
a = stack.pop()
b = stack.pop()
val = binary_ops[token](a, b)
if val == 1:
return "Cannot divide by zero"
stack.push(val)
elif token in unary_ops:
a = stack.pop()
stack.push(unary_ops[token](a))
elif token in constants:
stack.push(constants[token])
else:
try:
stack.push(float(token))
except ValueError:
return "Bad token: {}".format(token)
if len(stack) != 1:
return "Expected 1 item in stack, instead got {} for line: {}".format(len(stack), line)
else:
return stack.peek()
def main():
for line in sys.stdin:
output = calculate(line)
sys.stdout.write("{}\n".format(output))
sys.stdout.flush()
if __name__ == '__main__':
main()
class Stack:
def __init__(self):
self.stack = []
def __len__(self):
return len(self.stack)
def is_empty(self):
return len(self.stack) == 0
def push(self, val):
self.stack.append(val)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment