Python 的 class (二)案例:整数集

一个案例:创建一个整数集

  1. 初始时集合是空的
  2. 每个整数只会在集合里出现一次
  3. 以列表的形式表示内部数据
  4. 外部接口(初步):往集合里插入某个数,判断某个数是否属于某个集合,移除集合中的某个数
  5. 外部接口(进阶):计算两个集合的交,并
class intset(object):
    def __init__(self):
        self.vals = []
    def __str__(self):
        self.vals.sort()
        return "{" + ','.join([str(e) for e in self.vals]) + "}"
    def member(self,e):
        return e in self.vals

    def inset(self,e):
        if not e in self.vals:
            self.vals.append(e)
    def remove(self,e):
        try:
            self.vals.remove(e)
        except:
            raise ValueError(str(e) + " is not found")

    def intersection(self,other):
        #定义集合的交集
        s1 = self.vals
        s2 = other.vals
        s3 = []
        for i in s1:
            if i in s2:
                s3.append(i)
        s3.sort()
        return "{" + ','.join([str(e) for e in s3]) + "}"
    def union(self,other):
        #定义集合的并集
        s1 = self.vals
        s2 = other.vals
        for i in s1:
            if not i in s2:
                s2.append(i)
        s2.sort()
        return "{" + ','.join([str(e) for e in s2]) + "}"
a = intset()
a.inset(1)
a.inset(3)
a.inset(5)
print(a)
#>>>{1,3,5}
b = intset()
b.inset(2)
b.inset(3)
b.inset(4)
print(b)
#>>>{2,3,4}

a.intersection(b)
a.union(b)
#>>>'{3}'
#>>>'{1,2,3,4,5}'

需要改进的地方:判断集合的交与并的方式不合理,有更加高效的办法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值