# Problem 6-1 0.0/15.0 points (graded) Solution

1.  You are given the following superclass. Do not modify this.

2.

3.  class Container(object):

4.      """ Holds hashable objects. Objects may occur 0 or more times """

5.      def __init__(self):

6.          """ Creates a new container with no objects in it. I.e., any object

7.              occurs 0 times in self. """

8.          self.vals = {}

9.      def insert(self, e):

10.         """ assumes e is hashable

11.             Increases the number times e occurs in self by 1. """

12.         try:

13.             self.vals[e] += 1

14.         except:

15.             self.vals[e] = 1

16.     def __str__(self):

17.         s = ""

18.         for i in sorted(self.vals.keys()):

19.             if self.vals[i] != 0:

20.                 s += str(i)+":"+str(self.vals[i])+"\n"

21.         return s

22.

23. Write a class that implements the specifications below. Do not override any methods of Container.

24.

25. class Bag(Container):

26.     def remove(self, e):

27.         """ assumes e is hashable

28.             If e occurs in self, reduces the number of

29.             times it occurs in self by 1. Otherwise does nothing. """

30.         # write code here

31.

32.     def count(self, e):

33.         """ assumes e is hashable

34.             Returns the number of times e occurs in self. """

35.         # write code here

36.

37.     For example,

38.

39.     d1 = Bag()

40.     d1.insert(4)

41.     d1.insert(4)

42.     print(d1)

43.     d1.remove(2)

44.     print(d1)

45.

46.     prints

47.

48.     4:2

49.     4:2

50.

51.     For example,

52.

53.     d1 = Bag()

54.     d1.insert(4)

55.     d1.insert(4)

56.     d1.insert(4)

57.     print(d1.count(2))

58.     print(d1.count(4))

59.

60.     prints

61.

62.     0

63.     3