解析python中的数学表达式并求解以找到答案 [英] parsing math expression in python and solving to find an answer

查看:16
本文介绍了解析python中的数学表达式并求解以找到答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程很陌生.这与python有关.所以思路是取一个表达式,比如3/5或者最多3/5*2(最多两个运算符,注意运算符可以是+、-、/、*中的任意一个)并求解.空格可以存在于表达式中的任何位置.

I am quite new to programming. This is in relation to python. So the idea is to take an expression such as 3/5 or, at most, 3/5*2(at most two operators, note that the operators can be any of +,-,/,*) and solve it. White space can exist anywhere within the expression.

用户输入表达式,比如说3/5,程序需要解出表达式并显示答案.我尝试过的内容如下.请注意,我只尝试了第一部分,一旦我可以正确拆分用户输入的原始表达式(这将是一个字符串),创建函数将是简单的部分:

The user enters the expression, say 3/5, and the program needs to solve the expression and display the answers. What I have tried is below. Note, I only have attempted the first part, once I can properly split the original expression that the user enters(which would be a string), creating functions would be the easy part:

expres= str(input("something:"))

ssplit= hit.partition("/")
onec= int((ssplit[0].lstrip()).rstrip())
twoc= (ssplit[1].lstrip()).rstrip()
threec= int((huns[2].lstrip()).rstrip())


print(onec,"...",twoc,"...",threec) #just a debug test print

所以上面,我可以将像 3/5 这样的表达式拆分为三个单独的字符串:3、/和 5.我还可以删除运算符/操作数前后的所有空格.我在拆分 4/5+6 等表达式时遇到问题,因为我无法为 ssplit[3] 或 ssplit[4] 输入代码,然后输入像 3/5 这样的表达式,因为它不会被定义.基本上我需要你帮助找出如何拆分像 3/4-6 等的表达式.我还需要有关 "ssplit= hit.partition("/")" 行的帮助,以便它查看输入的表达式并处理 +、- 和 *.任何和所有的帮助表示赞赏.另外,如果我上面的代码看起来很糟糕且效率低下,请批评我.谢谢!

So above, I can take an expression like 3/5 and split it into three separate strings:3 , /, and 5. I can also remove all whitespace before and after the operators/operands. I am having problems with splitting expressions like 4/5+6, Because I can't put code in for ssplit[3] or ssplit[4] and then enter an expression like 3/5, because it won't be defined. Basically I needed you help to find out how to split an expression like 3/4-6,etc. I also need help with the line "ssplit= hit.partition("/")" so that it will look at the entered expression and work with +,-, and * as well. Any and all help is appreciated. Also if my code above looks nasty and inefficient please give me criticism. Thanks!

注意我不能,也不想使用 eval.操作顺序是必需的.我不能使用复杂的命令.我需要保持简单,我能使用的最多的是字符串库,在字符串/整数/浮点数等和 if、and 等之间进行转换.声明.我也可以使用函数.

Note I can't, and wouldn't want to use eval. Order of operations is required. I cant use complicated commands. I need to keep it simple, the most I can use is string libraries, converting between strings/integers/floats etc. and if,and,etc. statements. I can also use functions.

推荐答案

如果我不打算依赖外部库,我会这样做:

If I wasn't going to rely on external libraries, I'd do it something like this:

def parse(x):
    operators = set('+-*/')
    op_out = []    #This holds the operators that are found in the string (left to right)
    num_out = []   #this holds the non-operators that are found in the string (left to right)
    buff = []
    for c in x:  #examine 1 character at a time
        if c in operators:  
            #found an operator.  Everything we've accumulated in `buff` is 
            #a single "number". Join it together and put it in `num_out`.
            num_out.append(''.join(buff))
            buff = []
            op_out.append(c)
        else:
            #not an operator.  Just accumulate this character in buff.
            buff.append(c)
    num_out.append(''.join(buff))
    return num_out,op_out

print parse('3/2*15')

它不是最优雅的,但它以合理的数据结构为您提供了碎片(就我而言)

It's not the most elegant, but it gets you the pieces in a reasonable data structure (as far as I'm concerned anyway)

现在代码来实际解析和评估数字——这将在浮点中完成所有事情,但很容易改变......

Now code to actually parse and evaluate the numbers -- This will do everything in floating point, but would be easy enough to change ...

import operator
def my_eval(nums,ops):

    nums = list(nums)
    ops = list(ops)
    operator_order = ('*/','+-')  #precedence from left to right.  operators at same index have same precendece.
                                  #map operators to functions.
    op_dict = {'*':operator.mul,
               '/':operator.div,
               '+':operator.add,
               '-':operator.sub}
    Value = None
    for op in operator_order:                   #Loop over precedence levels
        while any(o in ops for o in op):        #Operator with this precedence level exists
            idx,oo = next((i,o) for i,o in enumerate(ops) if o in op) #Next operator with this precedence         
            ops.pop(idx)                        #remove this operator from the operator list
            values = map(float,nums[idx:idx+2]) #here I just assume float for everything
            value = op_dict[oo](*values)
            nums[idx:idx+2] = [value]           #clear out those indices

    return nums[0]

print my_eval(*parse('3/2*15'))

这篇关于解析python中的数学表达式并求解以找到答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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