Guest User

Untitled

a guest
Oct 23rd, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.09 KB | None | 0 0
  1. import re
  2.  
  3.  
  4. class Polynomial:
  5. """
  6. Class for one-variable polynomial
  7. """
  8.  
  9. def __init__(self, **kwargs):
  10. if len(kwargs) == 1:
  11. if 'string' in kwargs:
  12. # single string input
  13. assert type(kwargs['string']) is str, 'Single "string" input should be a string'
  14. self.coeff = self.initialize_from_string(kwargs['string'])
  15.  
  16. elif 'coeff_x' in kwargs:
  17. # single list specifying the coefficients
  18. assert type(kwargs['coeff_x']) is list, 'Single "coeff_x" input should be a list'
  19. self.coeff = self.initialize_from_one_list(kwargs['coeff_x'])
  20.  
  21. else:
  22. raise ValueError('Invalid input')
  23.  
  24. elif len(kwargs) == 2:
  25. # 2 lists specifying the coefficients and corresponding degrees
  26.  
  27. assert 'coeff_x' in kwargs and 'degree_x' in kwargs, 'Please define coeff_x and degree_x as inputs'
  28. assert type(kwargs['coeff_x'] is list), 'Coefficients should be specified in list'
  29. assert type(kwargs['degree_x'] is list), 'Degrees should be specified in list'
  30. assert len(kwargs['coeff_x']) > 0, 'Number of coefficients should be at least 1'
  31. assert len(kwargs['coeff_x']) == len(kwargs['degree_x']), 'Size of coefficients and degrees should be equal'
  32. assert all([type(i) is int or type(i) is float for i in kwargs['coeff_x']]), \
  33. 'All coefficient should be number'
  34. assert all([type(i) is int for i in kwargs['degree_x']]), 'All degree should be non-negative integer'
  35.  
  36. self.coeff = self.initialize_from_lists(kwargs['coeff_x'], kwargs['degree_x'])
  37.  
  38. else:
  39. raise ValueError('Invalid input')
  40.  
  41. self.max_degree = max(self.coeff.keys())
  42. self.clear_coeff()
  43.  
  44. @staticmethod
  45. def initialize_from_lists(coeff, degree):
  46. return dict(zip(degree, coeff))
  47.  
  48. @staticmethod
  49. def initialize_from_one_list(coeff):
  50. # assume corresponding degrees are integers from 0
  51. number_of_parts = len(coeff)
  52. degree = [i for i in xrange(0, number_of_parts)]
  53.  
  54. return dict(zip(degree, coeff))
  55.  
  56. @staticmethod
  57. def initialize_from_string(coeff):
  58. coeff = coeff.replace(' ', '')
  59. coeff = re.split(r'([+-])', coeff)
  60.  
  61. coeff_dict = dict()
  62. sign = 1
  63.  
  64. for element in coeff:
  65. if element != '+' and element != '-' and element != '':
  66. try:
  67. match = re.match(r'(\d+\.*\d*)(x\^|\*x\^|x*)(\d*)$', element)
  68.  
  69. coefficient = sign * float(match.group(1))
  70.  
  71. if match.group(2) != '':
  72. if match.group(2) == 'x': # linear component
  73. if 1 in coeff_dict:
  74. coeff_dict[1] += coefficient
  75. else:
  76. coeff_dict[1] = coefficient
  77. else: # higher degree
  78. if int(match.group(3)) in coeff_dict:
  79. coeff_dict[int(match.group(3))] += coefficient
  80. else:
  81. coeff_dict[int(match.group(3))] = coefficient
  82. else: # constant
  83. if 0 in coeff_dict:
  84. coeff_dict[0] += coefficient
  85. else:
  86. coeff_dict[0] = coefficient
  87. except AttributeError:
  88. print 'Please check input string, it is invalid!'
  89.  
  90. elif element == '-':
  91. sign = -1
  92. elif element == '+':
  93. sign = 1
  94.  
  95. return coeff_dict
  96.  
  97. def clear_coeff(self):
  98. delete = []
  99. for key, value in self.coeff.iteritems():
  100. if value == 0:
  101. delete.append(key)
  102.  
  103. for k in delete:
  104. del self.coeff[k]
  105.  
  106. def evaluate(self, variable):
  107. poly_value = 0.0
  108. for key, value in self.coeff.iteritems():
  109. poly_value += value * variable ** key
  110.  
  111. return poly_value
  112.  
  113. def differentiate(self):
  114. new_coeffs = dict()
  115. for key in self.coeff.iterkeys():
  116. new_coeffs[key - 1] = self.coeff[key] * key
  117.  
  118. self.coeff = new_coeffs
  119.  
  120. self.max_degree -= 1
  121. self.clear_coeff()
  122.  
  123. if __name__ == "__main__":
  124.  
  125. # Test list input
  126. coefficients = [1, -2, 6, 3, 4]
  127. degrees = [0, 5, 4, 1, 2]
  128. print 'my_polynom'
  129. my_polynom = Polynomial(coeff_x=coefficients, degree_x=degrees)
  130. print my_polynom.coeff
  131. print my_polynom.evaluate(3)
  132. my_polynom.differentiate()
  133. print my_polynom.coeff
  134. print my_polynom.evaluate(3)
  135.  
  136. # Test string input
  137. print 'my_polynom2'
  138. my_polynom2 = Polynomial(string='- 2x^3 + 1 + 6x + 3x^4')
  139. print my_polynom2.coeff
  140. my_polynom2.differentiate()
  141. print my_polynom2.coeff
  142.  
  143. print 'my_polynom3'
  144. my_polynom3 = Polynomial(string='-3.5-2x^3+6x^1+3x^4+5x^3')
  145. print my_polynom3.coeff
  146.  
  147. # Test single list input
  148. print 'my_polynom4'
  149. my_polynom4 = Polynomial(coeff_x=coefficients)
  150. print my_polynom4.coeff
Add Comment
Please, Sign In to add comment