python 集合

 面向对象的集合:

#coding:utf-8
__author__ = 'similarface'
class Set:
    '''
    list实现集合,及其集合操作
    '''
    def __init__(self,value=[]):
        self.data=[]
        self.concat(value)

    def intersect(self,other):
        '''
        集合交集操作
        :param other:
        :return:交集
        '''
        res=[]
        for x in self.data:
            #x in 会调用__getitem__
            if x in other:
                res.append(x)
        return Set(res)

    def union(self,other):
        '''
        集合并集操作
        :param other:
        :return:并集
        '''
        #复制自身的一个列表
        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
    a.data
    b.data

#coding:utf-8
__author__ = 'similarface'
from DataStruct.set import Set
'''
使用字典将集合性能优化为线性的  该类继承上面的Set类
'''
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):
        '''
        求交集操作
        :param other:
        :return:交集
        '''
        res={}
        for x in other:
            if x in self.data:
                res[x]=None
        return Set(res.keys())

    def union(self,other):
        '''
        求并集操作
        :param other:
        :return:并集
        '''
        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
    a.data
    b.data

 

posted @ 2016-01-13 16:11  similarface  阅读(341)  评论(0编辑  收藏  举报