Question

python 3 inheritance

5. (6 pts) Define a class named bidict (bidirectional dict) derived from the dict class; in addition to being a regular dictiFinally, _rdict should never store a key that is associated with an empty set-setitem_ and _del item-must ensure this invaria

Define a class named bidict (bidirectional dict) derived from the dict class; in addition to being a regular dictionary (using inheritance), it also defines an auxiliary/attribute dictionary that uses the bidict’s values as keys, associated to a set of the bidict’s keys (the keys associated with that value). Remember that multiple keys can associate to the same value, which is why we use a set: since keys are hashable (hashable = immutable) we can store them in sets. Finally, the bidict class stores a class attribute that keeps track of a list of all the objects created from this class, which two static functions manipulate.

Define the class bidict with the following methods (some override dict methods); you may also add helper methods: preface them with single underscores):

• __init__ (self,initial =[],**kargs): initializes the dict in the base class and also creates an auxiliary dictionary (I used a defaultdict) named _rdict (reversedict: you must use this name for the bsc to work correctly) whose key(s) (the values in the bidict) are associated with a set of values (their keys in thebidict): initialize _rdict by iterating through the newly initialized dictionary.

For a bidict to work correctly, its keys and their associated values must all be hashable. We define any object as hashable if it (a1) has a __hash__ attribute, and (a2) the attribute’s value is not None; also (b) if the object is iterable (has an __iter__ attribute) then every value iterated over is also hashable (by this same definition). Also note that str is hashable as a special case: if we apply the above definition it will create infinite recursion because every value that we iterate over in a str is a str that we can iterate over! Raise aValueError exception if any value is not hashable. Note you can use the hasattr and getattr functions (which I used in a recursive static helper method you should write with the name_is_hashable).

Finally, _rdict should never store a key that is associated with an empty set: __setitem__ and__delitem__ must ensure this invariant property (I wrote a helper method to help them do it).

For example if we define, bd = bidict(a=1,b=2,c=1) then _rdict stores {1: {'a', 'c'}, 2: {'b'}}. If I tried to construct bidict(a=[]) then __init__ would raise a ValueError exception. We will continue using this example below.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:

# bidirectional dictionary   

class bidict(dict):

  

# constructor

def __init__(self, inital=[], **kargs):

self.data = {}

if inital is not None:

self.update(inital)

if len(kargs):

self.update(kargs)

for k in self:

self.data[k] = 1

# function for set item

def __setitem__(self, key, value):

self[key] = value

# function for delete an item

def __delitem__(self, key):

self.pop(key)

self.data.pop(key)

# function for set item

def __call__(self, key):

if key in self:

return self.data[key]

else:

return 0

# function for clear

def clear(self):

self.clear()

self.data.clear()

# function for iteration

def __iter__(self):

return iter(self.data)

Solution: # bidirectional dictionary class bidict (dict): # constructor def init (self, inital- kargs) self.data if inital is

Add a comment
Know the answer?
Add Answer to:
python 3 inheritance Define a class named bidict (bidirectional dict) derived from the dict class; in...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PYTHON 3 Netflix stores a database that we can represent as a dict, whose keys are...

    PYTHON 3 Netflix stores a database that we can represent as a dict, whose keys are movie titles like 'Pscyho' (str); associated with each title is a set of 2-tuples. Each 2-tuple specifies the name of a reviewer (str) followed by a review score (int: a number 0-5); for example ('Alice', 5). A simple/small database can look like {'Psycho': {('Bob', 5), ('Carrie', 5), ('Alan', 1), ('Diane', 1)}, 'Amadeus': {('Carrie', 3), ('Diane', 3), ('Bob', 3)}, 'Up': {('Alan', 2), ('Diane', 5)}, 'Jaws':...

  • Hey guys I need help with this question with 3 sub-problems. f test remove short synonyms () Define the remove shorti s...

    Hey guys I need help with this question with 3 sub-problems. f test remove short synonyms () Define the remove shorti synonyms function which is passed a dictionary as a parameter- The keys of the parameter dictionary are words and the corresponding values are 1ists of synonyms (synonyms are words which have the same or nearly the same meaning). The function romoves all the eynonyme which have ous than 8 charactors from each corresponding list of synonyms-As well, the funet...

  • Code the following Program in C++ Define a class named Payment that contains a member variable...

    Code the following Program in C++ Define a class named Payment that contains a member variable of type float that stores the amount of the payment and appropriate accessor and mutator methods.    Also create a member function named paymentDetails that outputs an English sentence that describes the amount of the payment. Next define a class named CashPayment that is derived from Payment. This class should redefine the paymentDetails function to indicate that the payment is in cash. Include appropriate constructor(s)....

  • Python 3 Here is my question. In clock.py, define class Clock which will perform some simple...

    Python 3 Here is my question. In clock.py, define class Clock which will perform some simple time operations. Write an initializer function for Clock that will take three arguments from the user representing hour (in 24-hour format), minutes, and seconds. Each of these parameters should have a reasonable default value. You should check that the provided values are within the legal bounds for what they represent and raise a ValueError if they are not. if error_condition: raise ValueError("Descriptive error message")...

  • Iterators provide a systematic way to access all of the elements in a collection. To define...

    Iterators provide a systematic way to access all of the elements in a collection. To define an iterator, we need to add the __iter__() method to the class over which we want to iterate. Consider the following lines of code: odd_numbers = Odds(9) for num in odd_numbers: print(num) This code iterates over all the odd numbers less than or equal to 9 starting from the number 1. It assumes that the Odds class is iterable, i.e., it contains an __iter__()...

  • Please show all work and answer all parts using python, thanks! Instructions You will need to...

    Please show all work and answer all parts using python, thanks! Instructions You will need to create four files: • Shape2D.py - file containing a class definition containing properties all Shapes could possibly have. • Circle.py - file containing a class definition of a Circle that inherits from the Shape2D class. Square.py - file containing a class definition of a Square that inherits from the Shape2D class. • testFile.py - file containing pytest functions testing the Shape2D, Circle, and Square...

  • Python 3 Problem: I hope you can help with this please answer the problem using python...

    Python 3 Problem: I hope you can help with this please answer the problem using python 3. Thanks! Code the program below . The program must contain and use a main function that is called inside of: If __name__ == “__main__”: Create the abstract base class Vehicle with the following attributes: Variables Methods Manufacturer Model Wheels TypeOfVehicle Seats printDetails() - ABC checkInfo(**kwargs) The methods with ABC next to them should be abstracted and overloaded in the child class Create three...

  • Define a class named Payment that contains an instance variable "paymentAmount" (non-static member variable) of type...

    Define a class named Payment that contains an instance variable "paymentAmount" (non-static member variable) of type double that stores the amount of the payment and appropriate accessor (getPaymentAmount() ) and mutator methods. Also create a method named paymentDetails that outputs an English sentence to describe the amount of the payment. Override toString() method to call the paymentDetails() method to print the contents of payment amount and any other details not included in paymentDetails(). Define a class named CashPayment that is...

  • IN PYTHON Assignment Overview This assignment will give you experience on the use of classes. Understand...

    IN PYTHON Assignment Overview This assignment will give you experience on the use of classes. Understand the Application The assignment is to first create a class calledTripleString.TripleStringwill consist of threeinstance attribute strings as its basic data. It will also contain a few instance methods to support that data. Once defined, we will use it to instantiate TripleString objects that can be used in our main program. TripleString will contain three member strings as its main data: string1, string2, and string3....

  • ise 1. Create a new project named lab6 1. You will be implementing an IceCream class. For the class attributes, let&#39...

    ise 1. Create a new project named lab6 1. You will be implementing an IceCream class. For the class attributes, let's stick to flavor, number ofscoops, and price (in cents). Note that the price per scoop of any flavor is 99 cents. Therefore, allow the flavor and scoops to be set directly, but not the price! The price should be set automatically based on the number of scoops entered. Some other requirements i. A default constructor and a constructor with...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT