Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from stack import Stack
- import math
- import sys
- #binary operators
- def add(a, b):
- return a + b
- def multiply(a, b):
- return a * b
- def divide(a, b):
- return a / b
- def subtract(a, b):
- return a - b
- #unary operators
- def negate(a):
- return -a
- def square_root(a):
- return math.sqrt(a)
- bin_ops = {'+':add,
- '-':subtract,
- '*':multiply,
- '/':divide}
- unary_ops = {'n':negate,
- 'r':square_root}
- def calculator(line):
- tokens = line.split()
- stack = Stack()
- for t in tokens:
- if t not in bin_ops and t not in unary_ops:
- stack.push(float(t))
- elif t in bin_ops:
- b = stack.pop()
- a = stack.pop()
- stack.push(bin_ops[t](a, b))
- else:
- a = stack.pop()
- stack.push(unary_ops[t](a))
- return stack.top()
- def main():
- for line in sys.stdin:
- try:
- a = calculator(line.strip())
- print('{:.2f}'.format(a))
- except IndexError:
- print('Invalid RPN expression')
- if __name__ == '__main__':
- main()
- #Stack class
- class Stack(object):
- def __init__(self):
- self.l = []
- def push(self, e):
- self.l.append(e)
- def pop(self):
- return self.l.pop()
- def top(self):
- return self.l[-1]
- def is_empty(self):
- return len(self.l) == 0
- def __len__(self):
- return len(self.l)
Advertisement
Add Comment
Please, Sign In to add comment