Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
parse-lisp-expression.py 1.18 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-12 01:33 +08:00 . remove sensitive question description
# Time: O(n^2)
# Space: O(n^2)
class Solution(object):
def evaluate(self, expression):
"""
:type expression: str
:rtype: int
"""
def getval(lookup, x):
return lookup.get(x, x)
def evaluate(tokens, lookup):
if tokens[0] in ('add', 'mult'):
a, b = map(int, map(lambda x: getval(lookup, x), tokens[1:]))
return str(a+b if tokens[0] == 'add' else a*b)
for i in xrange(1, len(tokens)-1, 2):
if tokens[i+1]:
lookup[tokens[i]] = getval(lookup, tokens[i+1])
return getval(lookup, tokens[-1])
tokens, lookup, stk = [''], {}, []
for c in expression:
if c == '(':
if tokens[0] == 'let':
evaluate(tokens, lookup)
stk.append((tokens, dict(lookup)))
tokens = ['']
elif c == ' ':
tokens.append('')
elif c == ')':
val = evaluate(tokens, lookup)
tokens, lookup = stk.pop()
tokens[-1] += val
else:
tokens[-1] += c
return int(tokens[0])
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助