python编程求字符串s1和s2共同元素

定义一个方法intersect(self, other),返回一个新的intSet,包含同时出现在两个集合中的元素。换句话说,s1.intersect(s2),将返回同时包含在s1s2中元素的新intSet。若s1s2没有共同的元素该如何处理?

增加一个特殊方法__len__(self),若调用len(s),将返回s中元素的个数。

#-*- coding:UTF-8 -*-
__author__ = "zhangguodong"
__time__ ="2017.11.08"

class IntSet(object):
    def __init__(self):
        self.vals = set()

    def insert(self, n):
        self.vals.add(n)

    def member(self, n):
        return n in self.vals

    def remove(self, n):
        try:
            self.vals.remove(n)
        except:
            raise ValueError(str(n) + 'is not found')

    def __str__(self):
        vals = []
        for n in self.vals:
            vals.append(n)
        vals = map(str, vals)
        vals_str = ",".join(vals)
        return '{' + vals_str + '}'

    def intersect(self, other):
        intSet = IntSet()
        for i in self.vals:
            if other.member(i):
                intSet.insert(i)
        return intSet

    def __len__(self):
        return len(self.vals)

if __name__ == '__main__':
    s1 = IntSet()
    for i in range(0, 8):
        s1.insert(i)
    print "The set of s1 is:" + str(s1.vals)
    print "The length of s1:" + str(len(s1))
    print ""

    s2 = IntSet()
    str1 = [1,2,-1,-2,3.5,5,8,6]
    for i in str1:
        s2.insert(i)
    print "The set of s2 is:" + str(s2.vals)
    print "The length of s2:" + str(len(s2))
    print ""

    new_obj = s1.intersect(s2)
    print "The set of s1.intersect(s2) values is:"+str(new_obj)
    print "The length of s1.intersect(s2):"+str(len(new_obj))


你可能感兴趣的:(python学习)