Python collection, python
Object-oriented set:
# Coding: UTF-8 _ author _ = 'similarface' class Set: ''' list to implement the Set and its Set operation ''' def _ init _ (self, value = []): self. data = [] self. concat (value) def intersect (self, other): ''' set intersection operation: param other: return: intersection ''' res = [] for x in self. data: # x in calls _ getitem _ if x in other: res. append (x) return Set (res) def union (self, other): ''' Set union operation: param other: return: union ''' # copy its own list res = self. data [:] for x in other: if not x in res: res. append (x) return Set (res) def concat (self, value): for x in value: if not x in self. data: self. data. append (x) def _ len _ (self): return len (self. data) def _ getitem _ (self, item): return self. data [item] def _ and _ (self, other): return self. intersect (other) def _ or _ (self, other): return self. union (other) def _ repr _ (self): return '<Set:' + repr (self. data) + '> 'if _ name __= = "_ main _": users1 = Set (['jpan', 'ch', 'en']) users2 = Set (['ta ', 'ch', 'hk']) a = users1 & users2 B = users1 | users2 tf = 'ch' in users1. data B. data # coding: UTF-8 _ author _ = 'similarface' from DataStruct. set import Set ''' use the dictionary to optimize the Set performance to linear. This class inherits the above set class.
'''Class Set (Set): def _ init _ (self, value = []): self. data = {} self. concat (value) def concat (self, value): for x in value: self. data [x] = None def intersect (self, other): ''' intersection operation: param other: return: intersection ''' res = {} for x in other: if x in self. data: res [x] = None return Set (res. keys () def union (self, other): ''' evaluate the union set operation: param other: return: union set ''' res = {}for x in other: res [x] = None for x in self. data. keys (): res [x] = None return Set (res. keys () def _ getitem _ (self, item): return list (self. data. keys () [item] def _ repr _ (self): return '<Set: % r>' % list (self. data. keys () if _ name __= = "_ main _": users1 = Set (['jpan ', 'ch', 'en']) users2 = Set (['ta ', 'ch', 'hk']) a = users1 & users2 B = users1 | users2 tf = 'ch' in users1. data B. data