Last active
February 28, 2016 04:45
-
-
Save robperc/fbef7b1e8c83d9d6c588 to your computer and use it in GitHub Desktop.
Simple Reverse Polish notation calculator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Simple Reverse Polish notation calculator. | |
Uses a deque as a queue to push and pop operands from and eval to perform operations. | |
""" | |
from collections import deque | |
def isNumber(val): | |
""" | |
Validates input str is a real number. | |
Args: | |
val (str): Input str to validate. | |
Returns: | |
True if val is a real number. | |
False otherwise. | |
""" | |
if val.isdigit(): | |
return True | |
try: | |
float(val) | |
except ValueError: | |
return False | |
return True | |
def getValidInput(): | |
""" | |
Validates user input. Prompts for new input if not valid. | |
Returns: | |
User input when it is valid. | |
""" | |
valid_ops = ('+', '-', '*', '/', '%') | |
inp = str(raw_input('> ')) | |
if (not isNumber(inp)) and (inp not in valid_ops) and (inp != 'done'): | |
print "Please enter valid input." | |
inp = getValidInput() | |
return inp | |
def runCalc(): | |
""" | |
Starts calculator and begins prompting user for input. | |
""" | |
print "Type 'done' to exit." | |
# Initialize queue for operands | |
queue = deque() | |
# Get initial input | |
inp = getValidInput() | |
while inp != "done": | |
# If it's a number push to queue... | |
if isNumber(inp): | |
queue.append(inp) | |
# ... otherwise it is an operator so pop operands from queue | |
elif len(queue) >= 2: | |
op = inp | |
cmd = "%s %s %s" % (queue.popleft(), op, queue.popleft()) | |
result = eval(cmd) | |
print result | |
queue.appendleft(result) | |
# If there aren't enough operands in queue then ignore operator. | |
else: | |
print "Not enough operands in queue to perform operation." | |
inp = getValidInput() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment