Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

is_valid_mapping(mapping): This function accepts an encoding dictionary (mapping

ID: 3709882 • Letter: I

Question

is_valid_mapping(mapping): This function accepts an encoding dictionary (mapping) and a message and determines if the encoding dictionary is valid (returning true or false depending on the answer). Encoding dictionaries are valid only if their keys are all the same length, their values are all the same length, their keys are unique, and their values are unique. You may assume keys and values are always non-empty strings.

Detour: Why? Keys and values both need to be unique so that, once a message is encoded, a message can be decoded. They have to be the same length because it’s hard to decode messages if they aren’t. For example, if your mapping is {'a':'y', 'ab':'xx', 'b':'z'} and your message is 'aabb', you can’t tell if the message encodes to 'yyzz' or 'yxxz'.

Explanation / Answer

def is_valid_mapping(mapping): key_set = set() value_set = set() k = '' v = '' for key in mapping.keys(): if key in key_set or (k != '' and len(key) != len(k)): return False key_set.add(key) k = key for value in mapping.values(): if value in value_set or (v != '' and len(value) != len(v)): return False value_set.add(value) v = value return True