Python方程式解析器 [英] Python equation parser
问题描述
我正在编写一个程序,该程序需要用户输入x的多项式函数.我正在使用Tkinter和python 2.5.
I'm writing a program which needs a user input for an polynomial function of x. I'm using Tkinter and python 2.5.
我有一个解析器方法,到目前为止,它采用输入的方程式并将其拆分为项,而不会删除符号.
I have a parser method which so far takes the inputted equation and splits it into terms without dropping the signs.
我想接受每个术语并解析它以获得(系数,度)的元组.例如,-2x ^ 3返回(-2,3).然后,我可以将它们添加到数组中,并在程序中进行相应的操作.
I want to take each term and parse it to get a tuple of the (coefficient, degree). For example, -2x^3 returns (-2,3). I can then add these to an array and manipulate them accordingly in the program.
有没有一种方法或标准模块可以做到这一点?
Is there a way or standard module that can do this?
这是解析方法的开始.
def parse(a):
termnum=[]
terms=[]
hi=[]
num1=0
num=0
f=list(a)
count=0
negative=False
coef=0.0
deg=0.0
codeg=[]
for item in f:
if (item=='-' or item=='+') and count!=0:
termnum.append(count)
count+=1
for item in termnum:
num1=num
num=item
current=''
while num1<num:
current=current+f[num1]
num1+=1
terms.append(current)
num1=num
num=len(f)
current=''
while num1<num:
current=current+f[num1]
num1+=1
terms.append(current)
print terms
parse('-x^2+3x+2x^3-x')
谢谢! 附言:我不想使用外部软件包.
Thanks! P.S I don't want to use external packages.
推荐答案
您可以使用正则表达式
import re
test = '-x^2+3x+2x^3-x'
for m in re.finditer( r'(-{0,1}\d*)x\^{0,1}(-{0,1}\d*)', test ):
coef, expn = list( map( lambda x: x if x != '' and x != '-' else x + '1' ,
m.groups( ) ))
print ( 'coef:{}, exp:{}'.format( coef, expn ))
输出:
coef:-1, exp:2
coef:3, exp:1
coef:2, exp:3
coef:-1, exp:1
这篇关于Python方程式解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!