Question
Please write the functions in P ython and also include explanation for each line of code and a snapshot of the code to allow for
Please write the functions in Python and also include explanation for each line of code and a snapshot of the code to allow for viewing of correct indentation, thank you.
Question 1 a):
Design a class named Polynomial to represent a polynomial object that contains 3 terms - The Polynomial class should contain a list of coefficients as a private data field where coefficients[0] represents ao, coefficients[1] represents a1 and coefficients[2] represents a2. - Implement the __init__() method for the Polynomial class. The initializer method takes three integers, starting with ao, to create a polynomial object. The default value for each coefficient is 1.
Test | Result |
p1 = Polynomial(1, 2, 3) p2 = Polynomial(1, 2, 3) print(p1 is p2) | False |
Question 1 b):
Add the __str__(self) method to the Polynomial class - The __str__(self) method is called automatically by Python whenever a Polynomial object is provided as input to the print() function. The function should return a string that represents the Polynomial object. The string returned by this method should use the ^ character to indicate exponentiation.
- If the exponent is 0, then 'x' is not printed (i.e., 2 rather than 2x^0)
- If the exponent is 1, then the exponent is not printed (i.e., 2x rather than 2x^1)
- Only terms with non-zero coefficients should be displayed
- If the coefficient of a term is 1, then the coefficient should be shown (i.e.1x + 2)
- If the coefficient of a term is negative, then a plus and a minus sign (i.e. x^2 + -2x + 2) should be shown.
- There should be a single space character on either side of a + sign that appears internal to the polynomial. The only exception to this rule is at the very start of the polynomial.
- The terms should appear in descending order of exponent value.
Test | Result |
p1 = Polynomial() print(p1) | 1x^2 + 1x + 1 |
p1 = Polynomial(3, 2, 0) print(p1) | 2x + 3 |
p1 = Polynomial(0, 2, 3) print(p1) | 3x^2 + 2x |
Question 1 c):
Add the evaluate(self, x) method to the Polynomial class. - The evaluate method takes an integer value, x , as a parameter and evaluates the value of the polynomial using that value for x.
Test | Result |
p = Polynomial(1, 2, 3) print(p) print(p.evaluate(2)) | 3x^2 + 2x + 1 17 |
p1 = Polynomial() print(p1) print(p1.evaluate(5)) | 1x^2 + 1x + 1 31 |
p1 = Polynomial(-3, 4, -2) print(p1) print(p1.evaluate(5)) | -2x^2 + 4x + -3 -33 |
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started