-
-
Save monkeymantra/03abd07b8a36f8691b4facb2623aedd4 to your computer and use it in GitHub Desktop.
My calc solution following the multiplication stack
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
__author__ = 'gregrice' | |
from functools import reduce | |
from itertools import zip_longest | |
import operator | |
OPS = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv} | |
def eval_string(calc_string): | |
parsed = calc_string.split(" ") | |
ops = [OPS[n] for n in parsed if n in OPS] | |
numbers = [int(n) for n in parsed if n not in OPS] | |
add_stack = [] | |
add_ops = [] | |
mult_stack = [] | |
mult_ops = [] | |
for n,o in zip_longest(numbers, ops): | |
if o in {operator.sub, operator.add}: | |
if mult_stack: | |
mult_stack.append(n) | |
cleared_stack = clear_op_stack(mult_stack, mult_ops) | |
add_stack.append(cleared_stack) | |
mult_stack, mult_ops = [], [] | |
else: | |
add_stack.append(n) | |
add_ops.append(o) | |
else: | |
mult_stack.append(n) | |
mult_ops.append(o) | |
add_stack.append(clear_op_stack(mult_stack, mult_ops)) | |
return int(clear_op_stack(add_stack, add_ops)) | |
def clear_op_stack(numbers, ops): | |
if not numbers: | |
return 0 | |
else: | |
first = numbers[0] | |
remaining = numbers[1:] | |
return reduce(lambda x, y: y[0](x, y[1]), zip(ops, remaining), first) | |
if __name__ == "__main__": | |
print(eval_string("1 + 2 * 3 * 4 / -2 + 1 + 0")) | |
print(eval_string("1 + 2 + 3")) | |
print(eval_string("1")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment