Data Structures and Algorithms with Object-Oriented Design Patterns in Python
next up previous index

Implementing Sets

 

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 gif. (See Figure gif). In general, a searchable container can hold arbitrary objects. However, in this chapter we will assume that the elements of a set are integers.

   figure27625
Figure: Object class hierarchy

Program gif defines the Set class. The abstract Set class extends the abstract SearchableContainer class defined in Program gif. 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.

   program27652
Program: Abstract Set class.

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 gif. In addition to self, it takes a single argument, n, which specifies that the universal set shall be tex2html_wrap_inline66641.


next up previous index

Bruno Copyright © 2003, 2004 by Bruno R. Preiss, P.Eng. All rights reserved.