Created
February 1, 2017 06:17
-
-
Save HackerEarthBlog/6465f93e1ca155ded5e8b0c8294f16ba to your computer and use it in GitHub Desktop.
FIle object to put a character back into the input buffer
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
from buffer import UngetableInput | |
token_stream = UngetableInput() | |
def expression(): | |
val = None | |
ch = token_stream.getc() | |
while ch == ' ': | |
ch = token_stream.getc() | |
if ch in {'-', '+', '.'} or ch.isdigit(): | |
token_stream.ungetc(ch) | |
val = number() | |
if type(val) == str: | |
return 'Error' | |
elif ch == '(': | |
op = operator() | |
exp1 = expression() | |
exp2 = expression() | |
if type(exp1) == str or type(exp2) == str: | |
return 'Error' | |
ch = token_stream.getc() | |
while ch == ' ': | |
ch = token_stream.getc() | |
if ch != ')': | |
return 'Invalid syntax.' | |
val = calc(op, exp1, exp2) | |
else: | |
return 'Invalid token.' | |
return val | |
def number(): | |
try: | |
n = float(token_stream.getword()) | |
except ValueError: | |
return 'Number expected.' | |
return n | |
def operator(): | |
op = token_stream.getc() | |
while op == ' ': | |
op = token_stream.getc() | |
if op in {'+', '-', '*', '/'}: | |
return op | |
else: | |
return 'Operator expected.' | |
def calc(op, exp1, exp2): | |
if op == '+': | |
return exp1 + exp2 | |
elif op == '-': | |
return exp1 - exp2 | |
elif op == '*': | |
return exp1 * exp2 | |
elif op == '/': | |
if exp2 == 0: | |
return 'Division by zero not allowed.' | |
return exp1 / exp2 | |
else: | |
return 'Unknown operator' | |
while True: | |
try: | |
print('> ', end='') | |
r = expression() | |
try: | |
v = float(r) | |
except ValueError: | |
print(r) | |
else: | |
print('=', v) | |
except EOFError: | |
exit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment