0

Define a Python class Polynomial which provides methods for performing algebraic operations on polynomials. Your class should behave as described in the following sample transcript:

>>> p1 = Polynomial([1, 2, 3])
>>> p1
1.000 z**2 + 2.000 z + 3.000
>>> p2 = Polynomial([100, 200])
>>> p1.add(p2)
1.000 z**2 + 102.000 z + 203.000
>>> p1 + p2
1.000 z**2 + 102.000 z + 203.000
>>> p1(1)
6.0
>>> p1(-1)
2.0
>>> (p1 + p2)(10)
1323.0
>>> p1.mul(p1)
1.000 z**4 + 4.000 z**3 + 10.000 z**2 + 12.000 z + 9.000
>>> p1 * p1
1.000 z**4 + 4.000 z**3 + 10.000 z**2 + 12.000 z + 9.000
>>> p1 * p2 + p1
100.000 z**3 + 401.000 z**2 + 702.000 z + 603.000
>>> p1.roots()
[(-1+1.4142135623730947j), (-1-1.4142135623730947j)]
>>> p2.roots()
[-2.0]
>>> p3 = Polynomial([3, 2, -1])
>>> p3.roots()
[-1.0, 0.33333333333333331]
>>> (p1 * p1).roots()
Order too high to solve for roots.

How would you go about designing this function so it can take polynomials of different grades. I'm really lost.

Thanks.

Andrés
  • 51
  • 1
  • 5

1 Answers1

3

You can create a class with variable number of attributes:

class Var:
    def __init__(self,**kwargs):
        for attr in kwargs.keys():
            self.__dict__[attr] = kwargs[attr]




v = Var(name="Sam",age=22)
print(v.__dict__)
print(v.name)
print(v.age)

Output:

{'age': 22, 'name': 'Sam'}
Sam
22

But if you want to pass a list as an argument and assign each member of the list to an attribute inside the class, whose name is going to be a letter, ascending in every attribute, you can do something like:

class Var:
    def __init__(self,*args):
        keyVal = 97
        for attr in args:
            self.__dict__[chr(keyVal)] = attr
            keyVal+=1




v1 = Var(1,2,3)
print('Attributes of v1',v1.__dict__)
myList = [4,5]
v2 = Var(*myList)
print("attributes of v2",v2.__dict__)

Output:

('Attributes of v1', {'a': 1, 'c': 3, 'b': 2})
('attributes of v2', {'a': 4, 'b': 5})
YBathia
  • 894
  • 1
  • 8
  • 18
  • I'm sorry i do not know what __dict__ or kwargs means – Andrés Mar 02 '16 at 23:47
  • @AndrésRivero: kwargs means keyword arguments , in the form of name="Sam",age=22 . These kwargs can be accessed inside a function just like a dictionary, the dictionary in this case being kwargs. A simple explanation of python dictionary is given here: http://www.tutorialspoint.com/python/python_dictionary.htm – YBathia Mar 02 '16 at 23:49
  • Ok. But what if I want to pass a list as an argument. And assign each member of the list to an attribute inside the class, whose name is going to be a letter, ascending in every attribute, as in: `self.a = 3`, `self.b = 4` etc. – Andrés Mar 03 '16 at 01:13
  • @AndrésRivero: Added more content to my solution, this should answer your question – YBathia Mar 03 '16 at 04:24