Home > Net >  (class problem in python)I want to skip certain part strings if the coefficient is zero, how can i d
(class problem in python)I want to skip certain part strings if the coefficient is zero, how can i d

Time:04-08

In this question, we want to return the function like this result but i do not want the things like 0^5 occur(because 0^5 equal to 0 and i do not want to show that, how can I write a code to let system detect that the several part is 0? And when i want to use degree function in Class Poly, i want to the inserted poly number to be the highest coefficient, how can I do that? we can place the insert function later, that is my code:

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)

CodePudding user response:

Here is the code I think you want, the order of the coefficients is wrong but That wasn't the main issue.

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]))

output:

3x^2   2x^3   1x^4
  • Related