|
Data Structures and Algorithms
with Object-Oriented Design Patterns in Python |
As discussed above,
this chapter addresses the implementation of sets of integers.
A set is a collection of elements.
Naturally, we want to insert and withdraw objects from the collection
and to test whether a given object is a member of the collection.
Therefore, we consider sets as being derived
from the SearchableContainer class defined in Chapter
.
(See Figure
).
In general, a searchable container can hold arbitrary objects.
However, in this chapter we will assume that the elements
of a set are integers.

Figure: Object class hierarchy
Program
defines the Set class.
The abstract Set class extends
the abstract SearchableContainer class
defined in Program
.
Five abstract methods are declared--__or__, __and__, __sub__,
__eq__, and __le__.
These methods correspond to the various set operations discussed above.
That is,
__or__ computes the union,
__and__ computes the intersection,
__sub__ computes the set difference,
__eq__ tests for set equality, and
__le__ tests whether one set is a subset of the other.
The Set class also
defines an instance attribute called _universeSize.
This instance attribute is used to record the size of the universal set.
The __init__ method for the Set class
is given in Program
.
In addition to self,
it takes a single argument, n,
which specifies that the universal set shall be
.