Created
February 4, 2017 02:42
-
-
Save jeongsd/9ab03c5e12f3549fa54a7925e27eacb8 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
import math | |
import collections | |
import types | |
def main(): | |
quit = "Ctrl+Z, Enter" | |
prompt = "Enter an expression ({} to quit): ".format(quit) | |
current = types.SimpleNamespace(letter="A") | |
globalContent = global_context() | |
localContext = collections.OrderedDict() | |
while True: | |
try: | |
expression = input(prompt) | |
if expression: | |
calculate(expression, globalContent, localContext, current) | |
except EOFError: | |
print() | |
break | |
def global_context(): | |
print(dir(math)) | |
globalContent = globals().copy() | |
for name in dir(math): | |
if not name.startswith("_"): | |
globalContent[name] = getattr(math, name) | |
return globalContent | |
def calculate(expression, globalContent, localContext, current): | |
try: | |
result = eval(expression, globalContent, localContext) | |
update(localContext, result, current) | |
print(", ".join(["{}={}".format(variable, value) | |
for variable, value in localContext.items()]) | |
) | |
print("ANS={}".format(result)) | |
except Exception as e: | |
print(e) | |
def update(localContext, result, current): | |
localContext[current.letter] = result | |
current.letter = chr(ord(current.letter) + 1) | |
if current.letter > "Z": | |
current.letter = "A" | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment