在python中解析数学表达式并求解找到答案 [英] parsing math expression in python and solving to find an answer
问题描述
用户输入表达式,比如3/5,程序需要解析表达式并显示答案。我试过的是下面。注意,我只尝试了第一部分,一旦我可以正确分割用户输入的原始表达式(这将是一个字符串),创建函数将是很容易的部分:
expres = str(input(something:))
ssplit = hit.partition(/)
onec = int (ssplit [0] .lstrip())。rstrip())
twoc =(ssplit [1] .lstrip())。rstrip()
threec = int((huns [2] ())。rstrip())
打印(onec,...,twoc,...,threec)#just调试测试打印
以上所示,我可以使用像3/5这样的表达式,并将其分为三个独立的字符串:3,/和我也可以在操作符/操作数之前和之后删除所有的空格。因为我不能把代码放入ssplit [3]或者ssplit [4],而是像3/5这样的表达式,因为它不会被定义,所以我有分裂表达式的问题,如4/5 + 6。基本上我需要你帮忙找出如何拆分3 / 4-6等表达式。我还需要帮助 ssplit = hit.partition(/)
,以便它将查看输入的表达式,并使用+, - 和*以及。任何和所有的帮助是赞赏。另外,如果我的代码看起来很讨厌和低效,请给我批评。谢谢!
注意我不能,也不想使用eval。
需要操作顺序。
我不能使用复杂的命令。我需要保持简单,我可以使用的最多的是字符串库,在字符串/整数/浮点数之间转换,以及如果和等等。声明。我也可以使用函数。
如果我不依赖外部库,我会做一些类似这是:
def parse(x):
operators = set('+ - * /')
op_out = []#这个持有在字符串中找到的运算符(从左到右)
num_out = [] #this保存在字符串中找到的非运算符(从左到右)
buff = []
for x中的c:#examine一次1个字符
如果运算符中的c:
#found一个运算符。我们在buff中累积的一切都是
#a singlenumber。加在一起,把它放在`num_out`里。
num_out.append(''。join(buff))
buff = []
op_out.append(c)
else:
#not一个运算符。只是在buff中积累这个角色。
buff.append(c)
num_out.append(''。join(buff))
返回num_out,op_out
打印解析('3/2 * 15')
这不是最优雅的,但它可以让您在合理的数据结构中就我所关心的)
现在的代码实际上解析和评估数字 - 这将做所有的浮点数,但会很容易改变...
import operator
def my_eval(nums,ops):
nums = list(nums)
ops = list(ops)
operator_order =('* /','+ - ')#precedence从左到右。同一指数的运营商具有相同的前提。
#map运算符到函数。
op_dict = {'*':operator.mul,
'/':operator.div,
'+':operator.add,
' - ':operator.sub $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ ,oo = next((i,o)for i,o in enumerate(ops)if o in op)#Next运算符与此优先级
ops.pop(idx)#从运算符列表中删除此运算符
values = map(float,nums [idx:idx + 2])#在这里我假定float为所有
value = op_dict [oo](* values)
nums [idx:idx + 2 ] = [value] #clear out这些索引
返回nums [0]
打印my_eval(*解析('3/2 * 15'))
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.
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
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!
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屋!