Created
October 29, 2016 21:25
-
-
Save goldsborough/e0e72f87e8fec9cd72d26cfd0456c73d to your computer and use it in GitHub Desktop.
No idea what CTCI is finding hard here
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
import re | |
OPERATIONS = { | |
'*': lambda a, b: a * b, | |
'/': lambda a, b: a / b, | |
'+': lambda a, b: a + b, | |
'-': lambda a, b: a - b, | |
} | |
def perform_operation(numbers, op): | |
first = numbers.pop() | |
second = numbers.pop() | |
result = OPERATIONS[op](first, second) | |
numbers.append(result) | |
def calculate(equation): | |
# Turn into stack | |
numbers = [float(i) for i in reversed(re.findall(r'\d+', equation))] | |
operations = re.findall(r'[*/+-]', equation)[::-1] | |
while operations: | |
op = operations.pop() | |
if op in '*/': | |
perform_operation(numbers, op) | |
else: | |
temp = numbers.pop() | |
while operations and operations[-1] in '*/': | |
perform_operation(numbers, operations.pop()) | |
numbers.append(temp) | |
perform_operation(numbers, op) | |
return numbers[-1] | |
def main(): | |
print(calculate('2*3+5/6*3+15')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment