How long it's been since I've made a submission here. Just about two years, in fact.
Anyways, I digress. In my down time between semesters I like to dabble with smaller code snippets, using languages I'm unfamiliar with, as opposed to undertaking bigger projects. This is but one snippet that I've decided to pluck from my collection. It is one of my favorites for a number of reasons, but I particularly like the stack implementation which provides a simple yet robust method of evaluating postfix expressions.
For those of you who are not familiar with "Postfix," or "Reverse Polish," notation -- it is another way of writing every day math expressions. "1 + 2 * 4" becomes "1 2 4 * +" so on and so forth. Postfix notation is commonly used behind the scenes by several programming languages, applications, devices, APIs, and other similar constructs. This is largely attributed to it's low complexity, and high efficiency.
Here's the code:
print "Post-fix Calculator"
print "For help, type \"help\" or \"?\""
while True:
str_in = raw_input("> ")
tokens = str_in.split(" ")
stack = []
if tokens[0] == "help" or tokens[0] == "?":
print "Post-fix calculator takes in post-fix formatted equations and evaluates them."
print "Input should be formatted in such a way that the equation can be evaluated fully."
print "Ex. \"1 2 + 4 *\" equals \"12\""
elif tokens[0] == "quit" or tokens[0] == "q":
break
else:
while len(tokens) > 0:
item = tokens.pop(0)
if item.isdigit():
stack.append(int(item))
elif item == "+":
if len(stack) > 1:
stack.append(stack.pop() + stack.pop())
else:
#ERROR
print "ERROR: Invalid expression. Not enough input."
break
elif item == "-":
if len(stack) > 1:
tmp = stack.pop()
stack.append(stack.pop() - tmp)
else:
#ERROR
print "ERROR: Invalid expression. Not enough input."
break
elif item == "*":
if len(stack) > 1:
stack.append(stack.pop() * stack.pop())
else:
#ERROR
print "ERROR: Invalid expression. Not enough input."
break
elif item == "/":
if len(stack) > 1:
tmp = stack.pop()
stack.append(stack.pop() / tmp)
else:
#ERROR
print "ERROR: Invalid expression. Not enough input."
break
elif item == "^":
if len(stack) > 1:
tmp = stack.pop()
stack.append(pow(stack.pop(), tmp))
else:
#ERROR
print "ERROR: Invalid Expression. Not enough input."
break
else:
#ERROR
break
print stack.pop()
Here are a few examples:
1 + 2 * 4
1 2 4 * +
9
5 ^ 2
5 2 ^
25
2 ^ 5 * 4
2 5 ^ 4 *
128
Feel free to leave a reply. I'd be happy to help with any questions you may have, or we can have a good old fashioned conversation.
Enjoy, my friends. :^)
EDIT: Fixed Markdown derps. (Nice job on the new-ish Markdown editor, Hawkee. Top notch work.)