问题
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.
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?
Here is the beginning of the parse method.
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.
回答1:
you can use regular expressions,
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 ))
output:
coef:-1, exp:2
coef:3, exp:1
coef:2, exp:3
coef:-1, exp:1
回答2:
Look for "recursive descent parser". It's the canonical method for analysis of strings where some operator precedence is involved.
回答3:
It looks like you're implementing something that already exists, in python and other math languages. See for example:
http://www.gnu.org/software/octave/doc/interpreter/Solvers.html
http://stat.ethz.ch/R-manual/R-devel/library/base/html/solve.html
来源:https://stackoverflow.com/questions/20702737/python-equation-parser