Last active
November 9, 2015 08:49
-
-
Save AlbericC/2bc9d1c33cdbdb6925e0 to your computer and use it in GitHub Desktop.
This file contains 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
""" | |
""" | |
import operator as op | |
def eval_safer(s): | |
"""basic parsinig an evaluation of expressions.""" | |
ops = {'*': op.mul, | |
'+': op.add, | |
'-': op.sub, | |
'/': op.truediv, | |
'^': op.pow} | |
# get the numbers at the start of the string | |
current = [] | |
buffer = 0 | |
op_queued = None | |
for idx, c in enumerate(s.replace(' ', '')): | |
if c in '0123456789': | |
current.append(c) | |
elif s[idx] in ops: | |
print('i saw you want a {}'.format(ops[s[idx]])) | |
if op_queued: | |
# could also be op.add from the beginning, but meh. | |
buffer = op_queued(buffer, int(''.join(current))) | |
print('buffer is now {}'.format(buffer)) | |
else: | |
buffer = int(''.join(current)) | |
print('buffer is now {}'.format(buffer)) | |
op_queued = ops[s[idx]] | |
current = [] | |
else: | |
# return None on any unforseen character. | |
return None | |
if op_queued: # some work left ? | |
buffer = op_queued(buffer, int(''.join(current))) | |
else: | |
buffer = int(''.join(current)) | |
return buffer | |
def ask(): | |
while True: # iterate until `break` | |
in_usr = input("Please enter a positive integer: ") | |
processed = eval_safer(in_usr) | |
if isinstance(processed, (int, float)): | |
break | |
else: | |
print("nah, try again.") | |
print('you typed for {}'.format(processed)) | |
if __name__ == '__main__': | |
ask() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment