Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- class Polynomial:
- """
- Class for one-variable polynomial
- """
- def __init__(self, **kwargs):
- if len(kwargs) == 1:
- if 'string' in kwargs:
- # single string input
- assert type(kwargs['string']) is str, 'Single "string" input should be a string'
- self.coeff = self.initialize_from_string(kwargs['string'])
- elif 'coeff_x' in kwargs:
- # single list specifying the coefficients
- assert type(kwargs['coeff_x']) is list, 'Single "coeff_x" input should be a list'
- self.coeff = self.initialize_from_one_list(kwargs['coeff_x'])
- else:
- raise ValueError('Invalid input')
- elif len(kwargs) == 2:
- # 2 lists specifying the coefficients and corresponding degrees
- assert 'coeff_x' in kwargs and 'degree_x' in kwargs, 'Please define coeff_x and degree_x as inputs'
- assert type(kwargs['coeff_x'] is list), 'Coefficients should be specified in list'
- assert type(kwargs['degree_x'] is list), 'Degrees should be specified in list'
- assert len(kwargs['coeff_x']) > 0, 'Number of coefficients should be at least 1'
- assert len(kwargs['coeff_x']) == len(kwargs['degree_x']), 'Size of coefficients and degrees should be equal'
- assert all([type(i) is int or type(i) is float for i in kwargs['coeff_x']]), \
- 'All coefficient should be number'
- assert all([type(i) is int for i in kwargs['degree_x']]), 'All degree should be non-negative integer'
- self.coeff = self.initialize_from_lists(kwargs['coeff_x'], kwargs['degree_x'])
- else:
- raise ValueError('Invalid input')
- self.max_degree = max(self.coeff.keys())
- self.clear_coeff()
- @staticmethod
- def initialize_from_lists(coeff, degree):
- return dict(zip(degree, coeff))
- @staticmethod
- def initialize_from_one_list(coeff):
- # assume corresponding degrees are integers from 0
- number_of_parts = len(coeff)
- degree = [i for i in xrange(0, number_of_parts)]
- return dict(zip(degree, coeff))
- @staticmethod
- def initialize_from_string(coeff):
- coeff = coeff.replace(' ', '')
- coeff = re.split(r'([+-])', coeff)
- coeff_dict = dict()
- sign = 1
- for element in coeff:
- if element != '+' and element != '-' and element != '':
- try:
- match = re.match(r'(\d+\.*\d*)(x\^|\*x\^|x*)(\d*)$', element)
- coefficient = sign * float(match.group(1))
- if match.group(2) != '':
- if match.group(2) == 'x': # linear component
- if 1 in coeff_dict:
- coeff_dict[1] += coefficient
- else:
- coeff_dict[1] = coefficient
- else: # higher degree
- if int(match.group(3)) in coeff_dict:
- coeff_dict[int(match.group(3))] += coefficient
- else:
- coeff_dict[int(match.group(3))] = coefficient
- else: # constant
- if 0 in coeff_dict:
- coeff_dict[0] += coefficient
- else:
- coeff_dict[0] = coefficient
- except AttributeError:
- print 'Please check input string, it is invalid!'
- elif element == '-':
- sign = -1
- elif element == '+':
- sign = 1
- return coeff_dict
- def clear_coeff(self):
- delete = []
- for key, value in self.coeff.iteritems():
- if value == 0:
- delete.append(key)
- for k in delete:
- del self.coeff[k]
- def evaluate(self, variable):
- poly_value = 0.0
- for key, value in self.coeff.iteritems():
- poly_value += value * variable ** key
- return poly_value
- def differentiate(self):
- new_coeffs = dict()
- for key in self.coeff.iterkeys():
- new_coeffs[key - 1] = self.coeff[key] * key
- self.coeff = new_coeffs
- self.max_degree -= 1
- self.clear_coeff()
- if __name__ == "__main__":
- # Test list input
- coefficients = [1, -2, 6, 3, 4]
- degrees = [0, 5, 4, 1, 2]
- print 'my_polynom'
- my_polynom = Polynomial(coeff_x=coefficients, degree_x=degrees)
- print my_polynom.coeff
- print my_polynom.evaluate(3)
- my_polynom.differentiate()
- print my_polynom.coeff
- print my_polynom.evaluate(3)
- # Test string input
- print 'my_polynom2'
- my_polynom2 = Polynomial(string='- 2x^3 + 1 + 6x + 3x^4')
- print my_polynom2.coeff
- my_polynom2.differentiate()
- print my_polynom2.coeff
- print 'my_polynom3'
- my_polynom3 = Polynomial(string='-3.5-2x^3+6x^1+3x^4+5x^3')
- print my_polynom3.coeff
- # Test single list input
- print 'my_polynom4'
- my_polynom4 = Polynomial(coeff_x=coefficients)
- print my_polynom4.coeff
Add Comment
Please, Sign In to add comment