Advertisement
trds

classPolinom

Feb 3rd, 2021
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. import math
  2. class Polinom:
  3.     def __init__(self, gr, coef):
  4.         if (len(coef)-gr)==1:
  5.             self.grad=gr
  6.             coef.reverse()
  7.             self.coeficienti = coef
  8.         else:
  9.             raise Exception ("Parametrii incorecti")
  10.  
  11.     def __repr__(self):
  12.         g=self.grad
  13.         self.coeficienti.reverse()
  14.         v=self.coeficienti
  15.         self.coeficienti
  16.         s="{}x^{}".format(v[0],g)
  17.         for i in range (1, len(v)):
  18.             g=g-1
  19.             if v[i] >0 and i!=(len(v)-1):
  20.                 s=s+"+{}x^{}".format(v[i],g)
  21.             if v[i] <0 and i!=(len(v)-1):
  22.                 s=s+"+({})x^{}".format(v[i],g)
  23.             if i==(len(v)-1):
  24.                 s=s+"+{}".format(v[i])
  25.         return s
  26.  
  27.     def calcul(self,x):
  28.         suma=0
  29.         for i in range(0, len(self.coeficienti)):
  30.             monom=self.coeficienti[i]*x^i
  31.             suma=suma + monom
  32.         return suma
  33.  
  34.     def __add__(self, q):
  35.         if self.grad == q.grad:
  36.             v=[]
  37.             for i in range(0, len(self.coeficienti)):
  38.                 el=self.coeficienti[i]+q.coeficienti[i]
  39.                 v.append(el)
  40.             p = Polinom(self.grad,v)
  41.             return p
  42.  
  43.  
  44. p=Polinom(4,[5,2,-1,0,7])
  45. p2=Polinom(4,[2,5,-1,7,8])
  46. print (p)
  47. print (p.calcul(2))
  48. print(p+p2)
  49.  
  50.  
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement