Answered step by step
Verified Expert Solution
Question
1 Approved Answer
PYTHON Write a class that represents and defines methods, operators, and an iterator for the Bag class. Bags are similar to sets, and have similar
PYTHON
Write a class that represents and defines methods, operators, and an iterator for the Bag class. Bags are similar to sets, and have similar operations (of which we will implement just the most important) but unlike sets they can store multiple copies of items. We will store the information in bags as dictionaries (I suggest using a defaultdict) whose keys are associated with int values that specify the number of times the key occurs in the Bag. You must store Bags using this one data structure, as specified Details 1. Define a class named Bag in a module named bag.py 2. Define an_ init_method that has one parameter, an iterable of values that initialize the bag. Writing Bag0 constructs an empty bag. Writing Bag(l'd','a','b','d','c','b'.'d']) construct a bag with one 'a', two 'b's, one 'c', and three 'd's. Objects in the Bag class should store only the dictionary specified above: it should not store/manipulate any other self variables 3. Define a__repr__method that returns a string, which when passed to eval returns a newly constructed bag with the same valueto the object_repr_ was called on. For example, for the Bag in the discussion of_init the-repr method would print its result as Bag(l'a', 'c', 'b', 'b','d', 'd', 'd']). Bags like sets are not sorted, so these 7 values can appear in any order. We might require that information in the list is sorted, but not all values we might put in a bag may be ordered (and therefore not sortable): e.g.. a bag storing both string and int values Bag(T'a',1]) which is allowed Note: This method is used to test several other methods/operators in the batch self-check file; so it is critical to write it correctly 4. Define a_str_ method that returns a string that more compactly shows a bag. For example, for the Bag in the discussion of init the str , method would print its result as Bag(al1j, cl1j, b[2j, d[3]). Bags like sets are not sorted, so these 7 values can appear in any orderStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started