12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

My solution to the multiple-operand extension subclass looks like the classbelow (file multiset.py). It only needs to replace two methods in the original set.The class’ documentation string explains how it works:from setwrapper import Setclass MultiSet(Set):"""inherits all Set names, but extends intersectand union to support multiple operands; notethat "self" is still the first argument (storedin the *args argument now); also note that theinherited & and | operators call the new methodshere with 2 arguments, but processing more than2 requires a method call, not an expression:"""def intersect(self, *others):res = []for x in self:for other in others:if x not in other: breakelse:res.append(x)return Set(res)# Scan first sequence# For all other args# Item in each one?# No: break out of loop# Yes: add item to enddef union(*args):res = []for seq in args:for x in seq:if not x in res:res.append(x)return Set(res)# Self is args[0]# For all args# For all nodes# Add new items to resultYour interaction with the extension will look something like the following. Notethat you can intersect by using & or calling intersect, but you must callintersect for three or more operands; & is a binary (two-sided) operator. Also,note that we could have called MultiSet simply Set to make this change moretransparent if we used setwrapper.Set to refer to the original within multiset:>>> from multiset import *>>> x = MultiSet([1,2,3,4])>>> y = MultiSet([3,4,5])>>> z = MultiSet([0,1,2])>>> x & y, x | y # Two operands(Set:[3, 4], Set:[1, 2, 3, 4, 5])>>> x.intersect(y, z) # Three operandsSet:[]>>> x.union(y, z)Set:[1, 2, 3, 4, 5, 0]Part VI, Classes and OOP | 669

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!