python 与 类 合作添加加入移除项目

python working with classes adding joining removing items

做作业做这个,不明白这是怎么回事,所以解释步骤会有很大帮助。 这个问题很难理解,所以一直无法理解和尝试。 这是问题,分为3部分。 您将获得以下 superclass。不要修改这个。

class Container(object):
    """ Holds hashable objects. Objects may occur 0 or more times """
    def __init__(self):
        """ Creates a new container with no objects in it. I.e., any object 
            occurs 0 times in self. """
        self.vals = {}
    def insert(self, e):
        """ assumes e is hashable
            Increases the number times e occurs in self by 1. """
        try:
            self.vals[e] += 1
        except:
            self.vals[e] = 1
    def __str__(self):
        s = ""
        for i in sorted(self.vals.keys()):
            if self.vals[i] != 0:
                s += str(i)+":"+str(self.vals[i])+"\n"
        return s

写一个 class 来实现下面的规范。不要覆盖 Container 的任何方法。

class Bag(Container):
    def remove(self, e):
        """ assumes e is hashable
            If e occurs one or more times in self, reduces the number of 
            times it occurs in self by 1. Otherwise does nothing. """
        # write code here
def count(self, e):
    """ assumes e is hashable
        Returns the number of times e occurs in self. """
    # write code here

• 例如,d1 = Bag()

d1.insert(4)
d1.insert(4)
print(d1)
d1.remove(2)
print(d1)
prints 4:2
4:2

• 例如,d1 = Bag()

d1.insert(4)
d1.insert(4)
d1.insert(4)
print(d1.count(2))
print(d1.count(4))
prints 0
3

第二部分:

在 Bag 中编写一个方法,如果 b1 和 b2 是袋子,则 b1+b2 给出一个新袋子,表示两个袋子的并集。

• 例如,a = Bag()

a.insert(4)
a.insert(3)
b = Bag()
b.insert(4)
print(a+b)
prints 3:1
4:2

第三部分:

写一个 class 来实现下面的规范。不要覆盖 Container 的任何方法。

class ASet(Container):
    def remove(self, e):
        """assumes e is hashable
           removes e from self"""
        # write code here
def is_in(self, e):
    """assumes e is hashable
       returns True if e has been inserted in self and
       not subsequently removed, and False otherwise."""
    # write code here

• 例如,d1 = ASet()

d1.insert(4)
d1.insert(4)

d1.remove(2)
print(d1)

d1.remove(4)
print(d1)
prints 4:2 # from d1.remove(2) print

    # (empty) from d1.remove(4) print
• For example, d1 = ASet()
d1.insert(4)
print(d1.is_in(4))
d1.insert(5)
print(d1.is_in(5))
d1.remove(5)
print(d1.is_in(5))
prints True
True
False

谢谢。

如果你想写一个子class,你首先需要做的是了解你想要子class的class。因此,您需要做的第一件事就是了解 Container 的作用。

它有两种魔法方法,__init____str__,以及一种普通方法,insert。首先通过以下方式探索 insert

d1 = Container()
d1.insert(4)
print(d1)
d1.insert(2)
print(d1)
d1.insert(4)
print(d1)

你得到这个输出:

4:1

2:1
4:1

2:1
4:2

有 3 组响应,每个 print() 调用一组。你能看到发生了什么吗?当您插入 4 时,您会看到 4:1。如果您第二次插入 4,则会看到 4:2。换句话说,您看到的字符串表示形式是 value:count.

这是有效的,因为 Container 有成员 vals,它是一个字典。字典中的每一项都是 value:count,就像在字符串表示中一样。

您的第一个任务是编写一个子class Bag 来完成 Container 所做的一切,而且还具有方法 removecount .

方法 count 只是为 Container 中的一个值生成与 __str__ 为所有值生成的相同的答案。从字典中选择相应的值和 return 出现的次数。请注意,可以请求不存在的值的计数:return 0 在这种情况下。

class Bag(Container):
    def count(self, e):
        return self.vals.get(e,0)

检查这是否有效:

d1 = Bag()
d1.insert(4)
d1.insert(4)
print(d1.count(4))

这个位的另一半写remove,与insert相反。 insert 是做什么的?如果您要插入的值已经在 vals 中,它会增加计数,否则会将计数设置为 1。因此 remove 需要减少计数,如果它变为零,则删除该项目来自字典。请注意,可以尝试删除不存在的值:在这种情况下忽略它即可。

    def remove(self, e):
        if e not in self.vals:
            return
        self.vals[e] -= 1
        if self.vals[e] < 1:
            del(self.vals[e])

添加这段代码时要小心。缩进需要与 count.

对齐

现在您已经掌握了基础知识,您的下一个任务是编写一个 __add__ 方法来将两个袋子相加。换句话说,给定 Bags ab,你需要组合 a.valsb.vals。从 a 的副本开始,然后将 b 的内容添加到其中。您已经有一个方法来添加:使用方法 insert.

    def __add__(self, other):
        result = self.__class__()
        result.vals.update(self.vals)
        for value,count in other.vals.items():
            for _ in range(count):
                result.insert(value)
        return result

添加这段代码时要小心。缩进需要与 count.

对齐

你问题的第三部分实际上是第一部分的重复。 remove 方法相同。 is_in 方法与 count 相同,只是它 return 是 TrueFalse 而不是数字。