从字符串评估数学表达式并将其插入堆栈 [英] Evaluating mathematical expression from a string and inserting it on stack

查看:68
本文介绍了从字符串评估数学表达式并将其插入堆栈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个任意精度的计算器. 我在链接列表中表示数字(一个节点是一个数字),我想将它们存储在堆栈中. 但是,我似乎无法弄清楚如何在保持正确的数学运算顺序的同时将字符串形式的数学表达式分开.

I'm trying to build an arbitrary precision calculator. I represent numbers in linked lists (one node is a single digit), and I want to store them in a stack. However, I can't seem to figure out how to break the mathematical expression received as a string apart while keeping the right mathematical operations order.

例如,如果插入的表达式为6*8-2+8-8*9/4,则将数字表示为链表,并将其插入堆栈中,然后将运算符插入另一个堆栈中,然后我想为每次计算弹出参数并再次推送结果,依此类推,直到获得最终结果.

For example, if the inserted expression is 6*8-2+8-8*9/4, I'll represent numbers as linked lists and insert them into a stack, and insert the operators into a different stack, and then I want to pop the arguments for each calculations and push the result again, and so on until I get the final result.

我的问题是,我该如何实现它并仍然遵循数学运算顺序?

My question is, how can I implement this and still follow the mathematical operations order?

推荐答案

您可以尝试使用eval?

eval("6*8-2+8-8*9/4")

这会给你36

如果eval不可行,请尝试operator将字符串运算符转换为数学运算符:

If eval isn't feasible, maybe try operator to convert the string operators to mathematical ones:

import operator
operations = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.div,
    '%' : operator.mod,
    '^' : operator.xor
}

那么您也许可以遍历字符串并以这种方式求值? (现在,我将考虑循环部分,如果一切正常,请编辑我的答案)

Then maybe you could loop through the string and evaluate it that way? (I'll have a think about the looping part now and edit my answer if I get anything good)

这篇关于从字符串评估数学表达式并将其插入堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆