Set
  • union(S,T): returns the union of sets S and T
  • intersection(S,T): returns the intersection of sets S and T
  • difference(S,T): returns the difference of sets S and T
  • subset(S,T): a predicate that tests whether the set S is a subset of set T
  • #!/usr/bin/python
    
    class Set(object):
        def __init__(self):
            self._d = {}
    
        @property
        def d(self):
            return self._d
    
        @d.setter
        def d(self, d):
            self._d = d
    
        @d.deleter
        def d(self):
            del self._d
    
        def insert(self, v):
            """Insert an object into set"""
            self.d[v] = 0
    
        def union(self, s):
            temp = Set()
            for e in s.d:
                temp.insert(e)
    
            for e in self.d:
                temp.insert(e)
    
            return temp
    
        def intersection(self, s):
            temp = Set()
            for i in self.d:
                if s.d.has_key(i):
                    temp.insert(i)
    
            return temp
    
        def difference(self, s):
            temp = Set()
            for i in self.d:
                if not s.d.has_key(i):
                    temp.insert(i)
    
            return temp
    
        def subset(self, s):
            for i in self.d:
                if not s.d.has_key(i):
                    return False
    
            return True
    
        def __str__(self):
            s = ''
            for e in self.d:
                s += str(e)+' '
    
            return s
    
    def main():
        s = Set()
        s.insert(1)
        s.insert(2)
        s.insert(3)
        s.insert(4)
    
        s2 = Set()
        s2.insert(1)
        s2.insert(10)
        s2.insert(2)
        s2.insert(20)
    
        # union
        u = s.union(s2)
        print(u)
    
        # intersection
        i = s.intersection(s2)
        print(i)
    
        # difference
        d = s.difference(s2)
        print(d)
    
        # subset
        print(s.subset(s2))
    
    if __name__ == '__main__':
        main()
    			
    Reference
  • wiki