Programming Assignment 3 (Polynomials)
Write a Python program that reads polynomial addition and multiplication
problems from a file, whose name is provided in the command line, solves
these problems, and display the answers on the screen as well as write to a file,
named
f_answers.dat, where f is the input file name without the
.dat.
A sample input file,
poly.dat and the corresponding outputs are shown below:
Mac-mini:p3-polynomial raj$ more poly.dat
add -4:3,2:1,-3:0 9:4,8:3,4:2
mul 4:3,2:1,3:2,-3:0 9:4,8:3,4:2
Mac-mini:p3-polynomial raj$ python3 Poly.py poly.dat
( -4x^3 + 2x - 3 ) + ( 9x^4 + 8x^3 + 4x^2 ) = 9x^4 + 4x^3 + 4x^2 + 2x - 3
( 4x^3 + 3x^2 + 2x - 3 ) * ( 9x^4 + 8x^3 + 4x^2 ) = 36x^7 + 59x^6 + 58x^5 + x^4 - 16x^3 - 12x^2
Mac-mini:p3-polynomial raj$ more poly_answers.dat
9:4,4:3,4:2,2:1,-3:0
36:7,59:6,58:5,1:4,-16:3,-12:2
Assumptions and Hints
- We will consider polynomials in a single variable x with integer
coefficients: for instance, 3x^4 - 17x^2 - 3x + 5. Each term of
the polynomial can be represented as a pair of integers
(coefficient,exponent). The polynomial itself is then a list of
such pairs.
- For example, the polynomial introduced earlier is represented as
[(3,4),(-17,2),(-3,1),(5,0)]
- We have the following constraints to guarantee that each
polynomial has a unique representation:
- Terms are sorted in descending order of exponent in the list representation, however,
the input file may contain terms in any order.
- No term has a zero coefficient
- No two terms have the same exponent
- To be able to ADD and MULTIPLY polynomials, you can design a "dictionary"
representation
of the polynomials, with exponent as the "key" and the coefficient as the "value".
This representation will allow you to deal with different coefficients for
the same term in the addition or multiplication of polynomials.
Data Transformations in this problem:
From input file to list:
['add -4:3,2:1,-3:0 9:4,8:3,4:2', 'mul 4:3,2:1,3:2,-3:0 9:4,8:3,4:2']
[
('ADD', [(-4, 3), (2, 1), (-3, 0)], [(9, 4), (8, 3), (4, 2)]),
('MUL', [(4, 3), (3, 2), (2, 1), (-3, 0)], [(9, 4), (8, 3), (4, 2)])
]
Send to ADD function and receive back:
[(-4, 3), (2, 1), (-3, 0)], [(9, 4), (8, 3), (4, 2)]
{3: -4, 1: 2, 0: -3}
{4: 9, 3: 8, 2: 4}
{3: 4, 1: 2, 0: -3, 4: 9, 2: 4}
[(9, 4), (4, 3), (4, 2), (2, 1), (-3, 0)]
Send to MUL function and receive back:
[(4, 3), (3, 2), (2, 1), (-3, 0)], [(9, 4), (8, 3), (4, 2)]
{3: 4, 2: 3, 1: 2, 0: -3}
{4: 9, 3: 8, 2: 4}
{7: 36, 6: 59, 5: 58, 4: 1, 3: -16, 2: -12}
[(36, 7), (59, 6), (58, 5), (1, 4), (-16, 3), (-12, 2)]
Final answers:
[
[(9, 4), (4, 3), (4, 2), (2, 1), (-3, 0)],
[(36, 7), (59, 6), (58, 5), (1, 4), (-16, 3), (-12, 2)]
]