first part of question You are given the following superclass. Do not modify thi
ID: 3865470 • Letter: F
Question
first part of question
You are given the following superclass. Do not modify this.
Write a class that implements the specifications below. Do not override any methods of Container.
For example,
prints
For example,
prints
THIS is my answer of the first part of the question
Paste your entire class, including the definition, in the box below. Do not leave any debugging print statements.
Code Editor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
THis is the second part of the question i am not sure what to do
Write a method in Bag such that if b1 and b2 were bags then b1+b2 gives a new bag representing the union of the two bags.
For example,
prints
Paste your entire class for Bag with the new method, including the definition, in the box below. Do not leave any debugging print statements.
this is the third part of the question
Write a class that implements the specifications below. Do not override any methods of Container.
For example,
prints
For example,
prints
Paste your entire class, including the definition, in the box below. Do not leave any debugging print statements.
Code Editor
Please help me with indent it will be a problem because my indent's skill is not there yet thanks
Explanation / Answer
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. """ if e in self.vals: self.vals[e] -= 1 def count(self, e): """ assumes e is hashable Returns the number of times e occurs in self. """ if e not in self.vals: return 0 else: return self.vals[e] def __add__(self, other): """ assumes other is a Bag instance Returns dictionary of combined values between two Bag instances. """ combinedBag = Bag() combinedBag.vals = self.vals.copy() for e in other.vals: for i in range(other.vals[e]): combinedBag.insert(e) return combinedBag class ASet(Container): def remove(self, e): """assumes e is hashable removes e from self""" if e in self.vals: del self.vals[e] else: None 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.""" return e in self.vals
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.