数据存储模式是:生成一个队列,然后第一个数即P[0]是常数项,P[1],P[3],P[5]代表负幂次(P[1]是负一次幂,P[3]是负二次,P[5]是负三次,以此类推),P[2]是正1次,P[4]是正二次,所以有了数据结构编程就很容易了。
class P(object):
def __init__(self,a):
self.a=a
def __add__(self,p):
a,b=self.a, p.a
if len(a)<len(b):
weishu = len(b)
else:
weishu = len(a)
c=[]
for kkkk in range(weishu):
c.append(0)
if kkkk<len(a):
if kkkk<len(b):
c[kkkk] = a[kkkk]+b[kkkk]
else:
c[kkkk] = a[kkkk]
else:
c[kkkk] = b[kkkk]
return P(c)
def __sub__(self,p):
a,b=self.a, p.a
if len(a)<len(b):
weishu = len(b)
else:
weishu = len(a)
c=[]
for kkkk in range(weishu):
c.append(0)
if kkkk<len(a):
if kkkk<len(b):
c[kkkk] = a[kkkk]-b[kkkk]
else:
c[kkkk] = a[kkkk]
else:
c[kkkk] = -b[kkkk]
return P(c)
def __mul__(self,p):
a,b=self.a, p.a
if len(a)==1:
zuigaoci = len(b)
if len(b)==1:
zuigaoci = len(a)
else:
zuigaoci = len(a)+len(b)-1
c = []
for kkkk in range(zuigaoci):
c.append(0)
#考虑系数a[i],若其为i偶数,则其幂次为int(+i/2);
#若其位奇数,则其幂次为int(-(i+1)/2)
#幂次nn可以是0,负,正。
#若幂次为正,则乘完之后放在nn*2
#若幂次为负,则乘完之后放在-nn*2-1
for i in range(len(a)):
for j in range(len(b)):
if i%2==0:
ni = round(i/2)
else:
ni = round(-(i+1)/2)
if j%2==0:
nj = round(j/2)
else:
nj = round(-(j+1)/2)
nn = ni+nj
if nn > 0:
c[nn*2] += a[i]*b[j]
if nn ==0:
c[0] += a[i]*b[j]
if nn < 0:
c[-nn*2-1] += a[i]*b[j]
return P(c)
def _getStr(self,prefix='P(A) =',a=None):
a = self.a
aa = len(a)
s = ''
if len(a)==1:
s+=str(a[0])
return '{}{}'.format(prefix,s)
if aa%2==0:
zhengzuida = aa-2
fuzuida = aa-1
zhengweishu = round(aa/2)
fuweishu = round(aa/2)
else:
zhengzuida = aa-1
fuzuida = aa-2
zhengweishu = round((aa-1)/2+1)
fuweishu = round((aa-1)/2)
#从正到负挨个排
for i in range(zhengweishu-1):
if a[zhengzuida-2*i]==0:
continue
else:
if a[zhengzuida-2*i]>0:
s+=' +'
else:
s+=' -'
s+=str(abs(a[zhengzuida-2*i]))
s+='A^'
if (zhengzuida-2*i)%2==0:
s+=str( int((zhengzuida-2*i)/2))
if (zhengzuida-2*i)%2==1:
s+=str( int(-(zhengzuida-2*i+1)/2))
if a[0]!=0:
if a[0]>0:
s+=' +'+str(abs(a[0]))
else:
s+=' -'+str(abs(a[0]))
for i in range(fuweishu):
if a[2*i+1]==0:
continue
else:
if a[(2*i+1)]>0:
s+=' +'
else:
s+=' -'
s+=str(abs(a[2*i+1]))
s+='A^'
if (2*i+1)%2==0:
s+=str( int(-(2*i+1)/2))
if (2*i+1)%2==1:
s+='('+str( int(-(2*i+1+1)/2))+')'
return '{}{}'.format(prefix,s)
def Gettimes(n):
if n%2==0:
return n/2
else:
return -(n+1)/2
def __str__(self):
return self._getStr()
p1=P([1,2,3])
p2=P([0,1,0,1,-6,77,8])
p3=P([2,3,4,5])
print('p1:',p1)
print('p2:',p2)
print('p3:',p3)
print('p1+p2:',p1+p2)
print('p1-p2:',p1-p2)
print('p1*p3:',p1*p3)
输出结果:
p1: P(A) = +3A^1 +1 +2A^(-1)
p2: P(A) = +8A^3 -6A^2 +1A^(-1) +1A^(-2) +77A^(-3)
p3: P(A) = +4A^1 +2 +3A^(-1) +5A^(-2)
p1+p2: P(A) = +8A^3 -6A^2 +3A^1 +1 +3A^(-1) +1A^(-2) +77A^(-3)
p1-p2: P(A) = -8A^3 +6A^2 +3A^1 +1 +1A^(-1) -1A^(-2) -77A^(-3)
p1*p3: P(A) = +12A^2 +10A^1 +19 +22A^(-1) +11A^(-2) +10A^(-3)
还没有仔细检查错误,先这样吧。
参考了这个:https://zhidao.baidu.com/question/1051233755222477499.html