Package Bio :: Package Pathway :: Package Rep :: Module HashSet
[hide private]
[frames] | no frames]

Source Code for Module Bio.Pathway.Rep.HashSet

 1  # Copyright 2001 by Tarjei Mikkelsen. All rights reserved. 
 2  # This code is part of the Biopython distribution and governed by its 
 3  # license.  Please see the LICENSE file that should have been included 
 4  # as part of this package. 
 5   
6 -class HashSet:
7 """A set abstraction supporting the basic set operations. 8 9 This implementation requires that all elements are hashable, 10 which implies that elements must not mutate while contained. 11 """
12 - def __init__(self, elements = []):
13 """Initializes a new HashSet.""" 14 self.__elements = {} 15 for e in elements: 16 self.__elements[e] = 1
17
18 - def __contains__(self, element):
19 """Returns true iff this set contains element.""" 20 return self.__elements.has_key(element)
21
22 - def __eq__(self, set):
23 """Returns true iff x == y for all elements in self, set.""" 24 if not isinstance(set, HashSet): 25 return 0 26 for x in self.list(): 27 if not (x in set): return 0 28 for x in set.list(): 29 if not (x in self): return 0 30 return 1
31
32 - def __len__(self):
33 """Returns the number of elements in this set.""" 34 return len(self.__elements)
35
36 - def __ne__(self, set):
37 """Returns true iff this set is not equal to set.""" 38 return not self.__eq__(set)
39
40 - def __repr__(self):
41 """Returns a debugging string representation of this set.""" 42 return "HashSet(" + repr(self.list()) + ")"
43
44 - def __str__(self):
45 """Returns a string representation of this set.""" 46 return "{" + ",".join(map(str, self.list())) + "}"
47 48 # Element access: 49
50 - def add(self, element):
51 """Adds element to this set.""" 52 self.__elements[element] = 1
53
54 - def contains(self, element):
55 """Returns true iff this set contains element.""" 56 return self.__contains__(element)
57
58 - def remove(self, element):
59 """Removes element from this set.""" 60 try: 61 del self.__elements[element] 62 except KeyError: 63 pass
64
65 - def list(self):
66 """Returns the elements of this set in a list.""" 67 return self.__elements.keys()
68 69 # Information: 70
71 - def empty(self):
72 """Returns true iff this set is empty.""" 73 return len(self.__elements) == 0
74 75 # Set operations: 76
77 - def union(self, s):
78 """Returns the union of this set and s.""" 79 return HashSet(self.list() + s.list())
80
81 - def intersection(self, s):
82 """Returns the intersection of this set and s.""" 83 return HashSet(filter(lambda e,s=s: e in s, self.list()))
84
85 - def difference(self, s):
86 """Returns the difference of this set and s.""" 87 return HashSet(filter(lambda e,s=s: e not in s, self.list()))
88
89 - def cartesian(self,s):
90 """Returns the Cartesian product of this set and s.""" 91 p = [] 92 for i in self.list(): 93 for j in s.list(): 94 p.append((i,j)) 95 return HashSet(p)
96