Question: Need some help with Python Problem: - Dictionaries and Sets Problem 3: Compute the inverse of a dictionary A dictionary f can be thought of
Need some help with Python Problem:
- Dictionaries and Sets Problem 3: Compute the "inverse" of a dictionary A dictionary f can be thought of a mapping from keys to values, that is, as a one-to-many partial function f:KHV from a set K of keys to a set V of values. The domain Dom(f) CK of f is the set of keys of the dictionary f. The function f has an inverse iff (if and only if) it is one-to-one, that is, if every element of K is mapped to at most one element of V. The inverse function f-1 of f is defined by f-1(y) = x for every x such that x e Dom(f) and y= f(x). Write a function inverse that takes as input a dictionary f, and returns the inverse of f. If f is not one-to-one, you should raise the ValueError exception. Hints: You may want to accumulate the values (the elements to which keys are mapped) into a set, to check whether f is one-to-one or not. You can raise the ValueError exception via raise ValueError(). To form the result dictionary, you need all values to be hashable. Do not worry about this; Python will raise an exception if a type is not hashable. [] def inverse(f): """Returns the dictionary that represents the inverse function of f. It can be solved in 8 lines. "* # YOUR CODE HERE raise NotImplementedError() [ ] # Let's test the behavior for invertible mappings. assert_equal(inverse({'a': 1, 'b': 3, 'c': 2}), {1: 'a', 2: 'c', 3: '6'}) [ ] # Now for the exception raising. ok = False try: inverse({'a': 2, 'b': 2}) except ValueError: ok = True assert_true (ok)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
