Created
January 20, 2013 17:46
-
-
Save cesarkawakami/4580196 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
def crazy_computation(expression, values): | |
""" | |
given expression = ["a", "+", "b", "-", "c"] and values = {"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}, | |
return [-2, -1, 0] | |
""" | |
# taking care of the cases when one of the two first operands is a list | |
if not isinstance(expression[0], basestring): | |
intermediate = crazy_computation(expression[0], values) | |
return crazy_computation([intermediate] + expression[1:], values) | |
if not isinstance(expression[2], basestring): | |
intermediate = crazy_computation(expression[2], values) | |
return crazy_computation(expression[:2] + intermediate + expression[3:], values) | |
# now the first two operands are actual values. | |
intermediate = operate(expression[0], expression[1], expression[2]) | |
if len(expression) == 3: | |
return intermediate | |
else: | |
return crazy_computation([intermediate], expression[3:]) | |
def operate(a, op, b): | |
op_dict = { | |
"+": operator.add, | |
"-": operator.sub, | |
"*": operator.mul, | |
"/": operator.div, | |
} | |
return [op_dict[op](x, y) for x, y in zip(a, b)] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment