Description
COMP9021, Session 1, 2015
1 R Doubly linked lists
Modify the module linked_list.py which is part of the material of the 8th lecture into a module doubly_linked_list.py, to process lists consisting of nodes with a reference to both next and previous nodes, so with the class Node defined as follows.
class Node:
def __init__(self, value = None):
self.value = value self.next_node = None self.previous_node = None
2 Using linked lists to represent polynomials
Write a program that implements a class Polynomial. An object of this class is built from a string that represents a polynomial, that is, a sum or difference of monomials.
โข The leading monomial can be either an integer, or an integer followed by x, or an integer followed by xห followed by a nonnegative integer.
โข The other monomials can be either a nonnegative integer, or an integer followed by x, or an integer followed by xห followed by a nonnegative integer.
Spaces can be inserted anywhere in the string.
A monomial is defined by the following class:
class Monomial:
def __init__(self, coefficient = 0, degree = 0):
self.coefficient = coefficient self.degree = degree self.next_monomial = None
A polynomial is a linked list of monomials, ordered from those of higher degree to those of lower degree. An implementation of the __str__() method allows one to print out a polynomial.
Next is a possible interaction.
1
$ python …
>>> from polynomial import *
>>> Polynomial(โ-0โ) Incorrect input
>>> Polynomial(โ+0โ)
Incorrect input
>>> Polynomial(โ0x^-1โ)
Incorrect input
>>> Polynomial(โ2x + +2โ) Incorrect input
>>> Polynomial(โ2x + -2โ) Incorrect input
>>> Polynomial(โ2x – +2โ)
Incorrect input
>>> poly_0 = Polynomial(โ0โ)
>>> print(poly_0)
0
>>> poly_0 = Polynomial(โ0xโ)
>>> print(poly_0)
0
>>> poly_0 = Polynomial(โ0x^0โ)
>>> print(poly_0)
0
>>> poly_0 = Polynomial(โ0x^5โ)
>>> print(poly_0)
0
>>> poly_1 = Polynomial(โxโ)
>>> print(poly_1) x
>>> poly_1 = Polynomial(โ1xโ)
>>> print(poly_1) x
>>> poly_1 = Polynomial(โ1x^1โ)
>>> print(poly_1) x
>>> poly_2 = Polynomial(โ2โ)
>>> print(poly_2)
2
>>> poly_2 = Polynomial(โ2x^0โ)
>>> print(poly_2)
2
>>> poly_3 = Polynomial(โ1 + 2-3 +10โ)
>>> print(poly_3)
10
>>> poly_4 = Polynomial(โx + x – 2x -3x^1 + 3xโ)
>>> print(poly_4)
0
>>> poly_5 = Polynomial(โx + 2 + x – x -3x^1 + 3x + 5x^0โ)
>>> print(poly_5)
x + 7
>>> poly_6 = Polynomial(โ-2x + 7x^3 +x – 0 + 2 -x^3 + x^23 – 12x^8 + 45 x ^ 6 -x^47โ)
>>> print(poly_6)
-x^47 + x^23 – 12x^8 + 45x^6 + 6x^3 – x + 2
2
Reviews
There are no reviews yet.