gpt4 book ai didi

python - python中的算术表达式阅读器

转载 作者:太空宇宙 更新时间:2023-11-03 12:28:05 26 4
gpt4 key购买 nike

我正在尝试在 python 中创建一个表达式读取器来计算基本算术。

给定表达式 subtract(4,add(4,times(3,4))) --> -12

构建它的最 pythonic 方法是什么?我的方法是将表达式转换为字符串,然后创建许多 if 语句或切换案例以查找关键字,例如 addsubtracttimes。然后读取(,读取一个整数和逗号,然后再次运行if语句/switch case。如果遇到),即计算所需的算法时的最新重点工作。几乎在队列中存储关键工作和整数,并在 ) 找到了。这对我来说似乎有点太多了。我想知道 python 中是否有任何有用的内置函数可以使代码 pythonic 或更易于阅读

最佳答案

下面是一些可以帮助您开始使用 ast 的工作代码:

import ast

s = 'subtract(4,add(4,times(3,4)))'

# Probably better to use functions from the operator module here :-)
functions = {'subtract': lambda a,b: a-b,
'add': lambda a, b: a+b,
'times': lambda a,b: a*b}


def _evaluate(node):
if isinstance(node, ast.Num):
return node.n
elif isinstance(node, ast.Name):
return functions[node.id]
elif isinstance(node, ast.Call):
function = _evaluate(node.func)
return function(*[_evaluate(n) for n in node.args])
else:
raise ValueError('Unknown node type: %s', type(node))


def evaluate(s):
tree = ast.parse(s)
node = tree.body[0].value
return _evaluate(node)

print evaluate(s)

关于python - python中的算术表达式阅读器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20231306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com