Skip to content

Instantly share code, notes, and snippets.

@munguial
Last active October 15, 2015 05:22
Show Gist options
  • Save munguial/2aaf187f6ba3c61c9970 to your computer and use it in GitHub Desktop.
Save munguial/2aaf187f6ba3c61c9970 to your computer and use it in GitHub Desktop.
class Solution(object):
def diffWaysToCompute(self, input):
memo = {}
return self.buildTrees(input, memo)
def buildTrees(self, s, memo):
if s in memo:
return memo[s]
response = []
isOperand = True
for i in xrange(len(s)):
if s[i] in ['*', '+', '-']:
isOperand = False
left = self.buildTrees(s[:i], memo)
right = self.buildTrees(s[i + 1:], memo)
for left_tree in left:
for right_tree in right:
value = {'-': left_tree - right_tree,
'+': left_tree + right_tree,
'*': left_tree * right_tree}[s[i]]
response.append(value)
if isOperand:
return [int(s)]
else:
memo[s] = response
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment