Last active
June 18, 2016 18:10
-
-
Save schas002/074f42e5f8db88a23572c12ffc7b80b2 to your computer and use it in GitHub Desktop.
Pfxcalc, a prefix 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
""" | |
Pfxcalc | |
Programmed by zyabin101 | |
This code is hereby released into the public domain | |
""" | |
import ast | |
def lit_input(prompt): | |
""" | |
Safely evaluate input. Only returns the following Python literal | |
structures: strings, numbers, tuples, lists, dicts, booleans, and 'None'. | |
Raises ValueError for malformed strings. | |
""" | |
return ast.literal_eval(raw_input(prompt)) | |
def lorr_input(prompt, result): | |
inputted = raw_input(prompt) | |
return result if inputted == "result" else ast.literal_eval(inputted) | |
# Initialization | |
x = None | |
# Print welcome message | |
print "Welcome to Pfxcalc. Type 'help' for more information." | |
# Main program loop | |
while True: | |
# Get user input | |
cmd = raw_input(">> ") | |
# Process input | |
if cmd == "quit": | |
break | |
elif cmd == "result": | |
print x | |
elif cmd == "help": | |
helpmsg = """ | |
Pfxcalc is a prefix notation calculator. | |
Prefix notation, aka Polish notation, is a form of notation for logic, | |
arithmetic and algebra, like infix and postfix (reverse Polish) | |
notation. | |
The expression '+ 3 4' in prefix notation is as valid as '3 + 4' in | |
infix notation, as well as '3 4 +' in postfix notation. | |
Every computation starts with entering a command and the result is | |
printed *and* saved in a variable that can be recalled by entering | |
'result'. The variable can even be used as an argument for functions, | |
using the same command. | |
List of commands: | |
quit - self explanatory | |
result - recall the result variable | |
help - print this message | |
+ - add two numbers or sequences | |
- - subtract two numbers | |
* - multiply two numbers, or a sequence by a number | |
/ - divide two numbers | |
""" | |
print helpmsg | |
elif cmd == "+": | |
x = (lorr_input("Left side addend? ", x) + | |
lorr_input("Right side addend? ", x)) | |
print x # Implicitly output result | |
elif cmd == "-": | |
x = lorr_input("Minuend? ", x) - lorr_input("Subtrahend? ", x) | |
print x # Implicitly output result | |
elif cmd == "*": | |
x = (lorr_input("Left side factor? ", x) * | |
lorr_input("Right side factor? ", x)) | |
print x # Implicitly output result | |
elif cmd == "/": | |
x = lorr_input("Dividend? ", x) / lorr_input("Divisor? ", x) | |
print x # Implicitly output result | |
else: | |
print "Unrecognized command." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment