【问题标题】:python working with classes adding joining removing items [closed]python使用类添加加入删除项目[关闭]
【发布时间】:2017-07-29 05:07:22
【问题描述】:

这样做是为了做家庭作业,不明白它是如何工作的,所以用步骤解释会有很大帮助。 这个问题很难理解,所以无法理解和尝试。 这是问题,分为3部分。 您将获得以下超类。请勿修改。

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

编写一个实现以下规范的类。不要覆盖 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

第三部分:

编写一个实现以下规范的类。不要覆盖 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

谢谢。

【问题讨论】:

  • 更正你的缩进。
  • 这听起来更像是给你的教授或助教的问题——你基本上只是把整个问题集都扔在这里。如果您可以将其缩小到特定的内容并至少尝试解决此问题,那么它可能会成为主题。否则,这太宽泛了。
  • 第三部分写对了吗?
  • 我的问题很长,因为我不明白问题本身。我通过理解这个不知道如何发布来得出自己的答案。

标签: python class superclass python-3.6


【解决方案1】:

如果你想写一个子类,你需要做的第一件事就是理解你想要子类的类。因此,您需要做的第一件事就是了解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,就像在字符串表示中一样。

您的第一个任务是编写一个子类Bag,它可以完成Container 所做的所有事情,而且还具有removecount 方法。

count 方法只为Container 中的一个值生成与__str__ 为所有值生成的相同答案。从字典中选择对应的值并返回出现的次数。请注意,可以询问不存在的值的计数:在这种情况下返回 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 相同,只是它返回 TrueFalse 而不是数字。

【讨论】:

  • 在python 3中,你可以使用__class__()而不是self.__class__()
  • 你能给出is_in方法的确切代码吗?
  • 还没准备好尝试,嗯? return e in self.vals
  • 谢谢BoarGules 真的很详细,回答的类型很有帮助。
  • 另外,还有一个地方第三部分失败了,也许我的删除是错误的? d1.insert(4) d1.insert(4) d1.insert(4) d1.remove(4) print(d1.is_in(4))
猜你喜欢
  • 2017-01-17
  • 2011-07-09
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 2023-03-22
  • 2018-12-23
  • 2013-07-22
  • 2014-05-05
相关资源
最近更新 更多