These multi-operand functions work on sequences in the same way as the originals,
but they also support three or more operands. Notice the use of an else on the
intersection’s for loop here to detect common items. Also note that the last two ex-
amples in the following session work on lists with embedded compound objects: the
in tests used by the intersect and union functions apply equality testing to sequence
nodes recursively, as deep as necessary to determine collection comparison results:
C:\...\PP4E\Dstruct\Basic> python
>>> from inter2 import *
>>> s1, s2, s3 = 'SPAM', 'SLAM', 'SCAM'
>>> intersect(s1, s2)
['S', 'A', 'M']
>>> intersect(s1, s2, s3)
['S', 'A', 'M']
>>> intersect(s1, s2, s3, 'HAM')
['A', 'M']
>>> union(s1, s2), union(s1, s2, s3)
(['S', 'P', 'A', 'M', 'L'], ['S', 'P', 'A', 'M', 'L', 'C'])
>>> intersect([1, 2, 3], (1, 4), range(5)) # 3.X: range okay
[1]
>>> s1 = (9, (3.14, 1), "bye", [1, 2], "mello")
>>> s2 = [[1, 2], "hello", (3.14, 0), 9]
>>> intersect(s1, s2)
[9, [1, 2]]
>>> union(s1, s2)
[9, (3.14, 1), 'bye', [1, 2], 'mello', 'hello', (3.14, 0)]
Set Classes
The preceding section’s set functions can operate on a variety of objects, but they aren’t
as friendly as true objects. Among other things, your scripts need to keep track of the
sequences passed into these functions manually. Classes can do better: the class in
Example 18-10 implements a set object that can hold any type of object. Like the stack
classes, it’s essentially a wrapper around a Python list with extra set operations.
Example 18-10. PP4E\Dstruct\Basic\set.py
"multi-instance, customizable, encapsulated set class"
class Set:
def init(self, value = []): # on object creation
self.data = [] # manages a local list
self.concat(value)
def intersect(self, other): # other is any sequence type
res = [] # self is the instance subject
for x in self.data:
if x in other:
res.append(x)
return Set(res) # return a new Set
Implementing Sets | 1377