I need to load attributes for my Polynomial function, but it's load in a different form.
In the assignment, I have 3 forms values and I don't know how to read all of them. One of them is entered as list(), next one as elements and the last one is entered by a number of degrees of the polynomial (this is the greatest problem for me).
p1 = Polynomial([1,-3,0,2])
p2 = Polynomial(1,-3,0,2)
p3 = Polynomial(x0=1,x3=2,x1=-3)
>>> print(*p*)
2x^3 - 3x + 1
I already tried somethink like:
class Polynomial(object):
def __init__(self,*X):
self.x = X
def __str__(self):
index = 0
while True:
element = element+self.x[index]+"x^"+index
but thats don't expected the 3rd case and doesn't work with 1st and 2nd.
Using
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
In the first case, args
will contain [[1,-3,0,2]]
(so you want to manipulate args[0]
)
In the second case, args
will contain [1,-3,0,2]
And in the last case, kwargs
will contain { x0: 1, x3: 2, x1: -3 }
In that last case, to translate kwargs
into the list you want (IE [1,-3,0,2]
), you can do
[kwargs.get("x0", 0), kwargs.get("x1", 0), kwargs.get("x2", 0), kwargs.get("x3", 0)]
This will give you a list of the values of kwargs
you want at the right keys, or 0 if not found. (nicer way : [kwargs.get(x, 0) for x in ["x0","x1","x2","x3"]]
)