12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

lists to add just methods and operators related to set processing. Because all otherbehavior is inherited from the built-in list superclass, this makes for a shorter andsimpler alternative:class Set(list):def _ _init_ _(self, value = []):list._ _init_ _([])self.concat(value)def intersect(self, other):res = []for x in self:if x in other:res.append(x)return Set(res)def union(self, other):res = Set(self)res.concat(other)return resdef concat(self, value):for x in value:if not x in self:self.append(x)# Constructor# Customizes list# Copies mutable defaults# other is any sequence# self is the subject# Pick common items# Return a new Set# other is any sequence# Copy me and my list# value: list, Set...# Removes duplicatesdef _ _and_ _(self, other): return self.intersect(other)def _ _or_ _(self, other): return self.union(other)def _ _repr_ _(self): return 'Set:' + list._ _repr_ _(self)if _ _name_ _ == '_ _main_ _':x = Set([1,3,5,7])y = Set([2,1,4,5,6])print x, y, len(x)print x.intersect(y), y.union(x)print x & y, x | yx.reverse( ); print xHere is the output of the self-test code at the end of this file. Because subclassingcore types is an advanced feature, I’ll omit further details here, but I invite you totrace through these results in the code to study its behavior:% python setsubclass.pySet:[1, 3, 5, 7] Set:[2, 1, 4, 5, 6] 4Set:[1, 5] Set:[2, 1, 4, 5, 6, 3, 7]Set:[1, 5] Set:[1, 3, 5, 7, 2, 4, 6]Set:[7, 5, 3, 1]There are more efficient ways to implement sets with dictionaries in <strong>Python</strong>, whichreplace the linear scans in the set implementations shown here with dictionary indexoperations (hashing), and so run much quicker. (For more details, see Programming<strong>Python</strong>.) If you’re interested in sets, also take another look at the set object type we542 | Chapter 26: Advanced Class Topics

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

Saved successfully!

Ooh no, something went wrong!