Chapter 6 Exercise Set 2: Polynomials Module

In this exercise set we will develop a module named polynomial.py that will contain functions for representing and performing mathematical operations on polynomials of one argument.

Background

A polynomial of one argument is a mathematical expression of the form:

\[a_n x^n + a_{n-1} x^{n-1} + ... + a_1 x + a_0\]

where \(a_n\), \(a_{n-1}\), …, \(a_1\), and \(a_0\) are real numbers, \(a_n \neq 0\), and exponents are non-negative integers. \(a_n\), \(a_{n-1}\), …, \(a_0\) are called coefficients (with \(a_n\) called the leading coefficient). \(a_0\) is called the constant term and \(n\) is called the degree of the polynomial.

A polynomial function is a function that can be defined by evaluating a polynomial.

  1. Write a function print_poly(p) that takes lists representing a polynomial as described above and prints it out in “human readable” form.

    def print_poly(p):
        """
          >>> print_poly([4, 3, 2])
          4x^2 + 3x + 2
          >>> print_poly([6, 0, 5])
          6x^2 + 5
          >>> print_poly([7, 0, -3, 5])
          7x^3 - 3x + 5
          >>> print_poly([1, -1, 0, 0, -3, 2])
          x^5 - x^4 - 3x + 2
        """
    

    print_poly should pass the doctests above. Add it to a module named polynomial.py and put it in your $HOME/.local/lib/my_python directory.

  2. Write a function add_poly(p1, p2) that two lists, p1 and p2, representing polynomials and returns their sum.

    def add_poly(p1, p2):
        """
          >>> add_poly([3, 2, 1], [1, 2, 0])
          [4, 4, 1]
          >>> add_poly([1, 0, 2, 3, 1], [1, 2, 0, 0])
          [1, 1, 4, 3, 1]
        """
    
  3. Write a function read_poly(polystr) that takes a string representation of a polynomial of the kind generated by print_poly and returns a list of the polynomial coefficients (including 0’s) of the polynomial represented. While only one doctest is provided, you should add others using a TDD approach to development.

    def read_poly(polystr):
        """
          >>> read_poly('4x^2 + 3x + 2')
          [4, 3, 2]
        """
    
  4. Write a function mult_poly(p1, p2) that takes two polynomials as arguments and returns a polynomial with their product. Use a TDD approach to writing this function, beginning with doctests which make explicit what the output should be given two inputs before you implement the function.