【发布时间】: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