我正在编写一个程序,需要用户输入 x 的多项式函数。我正在使用 Tkinter 和 python 2.5。
我有一个解析器方法,到目前为止,它采用输入的方程并将其拆分为项而不丢弃符号。
我想获取每个术语并对其进行解析以获得(系数,度数)的元组。例如,-2x^3 返回 (-2,3)。然后我可以将它们添加到数组中并在程序中相应地操作它们。
有没有一种方法或标准模块可以做到这一点?
这里是解析方法的开始。
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')
谢谢! P.S 我不想使用外部包。
请您参考如下方法:
你可以使用正则表达式,
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
