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

Array and Bit-Vector Sets

In this section we consider finite sets over a finite universe. Specifically, the universe we consider is tex2html_wrap_inline66639, the set of integers in the range from zero to N-1, for some fixed and relatively small value of N.

Let tex2html_wrap_inline66651 be the universe. Every set which we wish to represent is a subset of U. The set of all subsets of U is called the power set  of U and is written tex2html_wrap_inline66659. Thus, the sets which we wish to represent are the elements of tex2html_wrap_inline66659. The number of elements in the set U, written |U|, is N. Similarly, tex2html_wrap_inline66669. This observation should be obvious: For each element of the universal set U there are only two possibilities: Either it is, or it is not, a member of the given set.

This suggests a relatively straightforward representation of the elements of tex2html_wrap_inline66659--an array of bool values, one for each element of the universal set. By using array subscripts in U, we can represent the set implicitly. That is, i is a member of the set if the tex2html_wrap_inline57847 array element is true.

Program gif introduces the class SetAsArray. The SetAsArray class extends the abstract Set class defined in Program gif. This class uses an array of length tex2html_wrap_inline66681 to represent the elements of tex2html_wrap_inline66659 where tex2html_wrap_inline66651.

   program27690
Program: SetAsArray class __init__ method.

Program gif defines the __init__ method for the SetAsArray class. In addition to self, the __init__ method takes a single argument tex2html_wrap_inline66687, which defines the universe and, consequently, the size of the array of bool values. The __init__ method creates the empty set by initializing all the elements of the bool array to False. Clearly, the running time of the __init__ method is O(N), where tex2html_wrap_inline66691.




next up previous index

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