如果系数为零,如何跳过某些部分字符串?
How to skip certain part strings if the coefficient is zero?
在这个问题中,我们想要return这个结果的函数但是我不希望发生像0^5这样的事情(因为0^5等于0而且我不想显示那,我要怎么写代码让系统检测到这几个部分都是0呢?而当我想用Class Poly
中的度数函数的时候,我要插入的多边形数是最高的系数,怎么才能我这样做吗?我们可以稍后放置插入功能,这是我的代码:
Class Poly():
def __init__(self,coe=[]):
self.coefficient=coe
def degree(self,poly=int()):
self.highestpoly=poly
def insert(self,polynomial,coefficient):
self.polynomial=polynomial
self.coefficient=coefficient #solve that later
def __str__(self):
e=self.coefficient[5]
c=self.coefficient[4]
a=self.coefficient[3]
b=self.coefficient[2]
z=self.coefficient[1]
d=self.coefficient[0]
epart=str(e)+str("^")+str(5)+'+'
cpart=str(c)+str("^")+str(4)+'+'
apart=str(a)+str("^")+str(3)+'+'
bpart=str(b)+str("^")+str(2)+'+'
zpart=str(c)+str("^")+str(1)+'+'
dpart=str(d)
return epart+cpart+apart+bpart+zpart+dpart
print(Poly([0,0,3,2,1,0]))
>>> tommy1111@infra04-wg013 lab11 % python3 -i mycode.py 0^5+1^4+2^3+3^2+1^1+0 (result)
这是我认为你想要的代码,系数的顺序是错误的,但这不是主要问题。
class Poly():
def __init__(self, coe=None):
if coe is None:
coe = []
self.coefficient = coe
def degree(self, poly=int()):
self.highestpoly = poly
def insert(self, polynomial, coefficient):
self.polynomial = polynomial
self.coefficient = coefficient # solve that later
def __str__(self):
p = []
for i, c in enumerate(self.coefficient):
if c != 0:
p.append(f"{c}x^{i}")
return " + ".join(p)
print(Poly([0,0,3,2,1,0]))
输出:
3x^2 + 2x^3 + 1x^4
在这个问题中,我们想要return这个结果的函数但是我不希望发生像0^5这样的事情(因为0^5等于0而且我不想显示那,我要怎么写代码让系统检测到这几个部分都是0呢?而当我想用Class Poly
中的度数函数的时候,我要插入的多边形数是最高的系数,怎么才能我这样做吗?我们可以稍后放置插入功能,这是我的代码:
Class Poly():
def __init__(self,coe=[]):
self.coefficient=coe
def degree(self,poly=int()):
self.highestpoly=poly
def insert(self,polynomial,coefficient):
self.polynomial=polynomial
self.coefficient=coefficient #solve that later
def __str__(self):
e=self.coefficient[5]
c=self.coefficient[4]
a=self.coefficient[3]
b=self.coefficient[2]
z=self.coefficient[1]
d=self.coefficient[0]
epart=str(e)+str("^")+str(5)+'+'
cpart=str(c)+str("^")+str(4)+'+'
apart=str(a)+str("^")+str(3)+'+'
bpart=str(b)+str("^")+str(2)+'+'
zpart=str(c)+str("^")+str(1)+'+'
dpart=str(d)
return epart+cpart+apart+bpart+zpart+dpart
print(Poly([0,0,3,2,1,0]))
>>> tommy1111@infra04-wg013 lab11 % python3 -i mycode.py 0^5+1^4+2^3+3^2+1^1+0 (result)
这是我认为你想要的代码,系数的顺序是错误的,但这不是主要问题。
class Poly():
def __init__(self, coe=None):
if coe is None:
coe = []
self.coefficient = coe
def degree(self, poly=int()):
self.highestpoly = poly
def insert(self, polynomial, coefficient):
self.polynomial = polynomial
self.coefficient = coefficient # solve that later
def __str__(self):
p = []
for i, c in enumerate(self.coefficient):
if c != 0:
p.append(f"{c}x^{i}")
return " + ".join(p)
print(Poly([0,0,3,2,1,0]))
输出:
3x^2 + 2x^3 + 1x^4