我有一个超类,如下所示:
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])+"
"
return s
我研究了一个子类:
class Bag(Container):
def remove(self, e):
""" assumes e is hashable
If e occurs in self, reduces the number of
times it occurs in self by 1. Otherwise does nothing. """
# write code here
if e in self.vals.keys():
self.vals[e] -= 1
def count(self, e):
""" assumes e is hashable
Returns the number of times e occurs in self. """
# write code here
if e not in self.vals.keys():
return 0
else:
return self.vals[e]
def __add__(self, other):
new_dict = other.vals
for e in self.vals.keys():
if e in other.vals.keys():
new_dict[e] += self.vals[e]
else:
new_dict[e] = self.vals[e]
return new_dict
def __str__(self):
s1 = ""
for i in sorted(self.new_dict.keys()):
s1 += str(i)+":"+str(self.new_dict[i])+"
"
return s1
运行测试用例时:
>一个=包()
> a.insert(3)
> a.insert(5)
> b =袋()
> b.insert(5)
> b.insert(5)
> b.insert(5)
>打印(a b)
我的输出是:
{3:1,5:4}
但是,预期输出应为:
3:1
5:4
如何获得正确的格式输出?非常感谢你!