is_valid_mapping(mapping): This function accepts an encoding dictionary (mapping
ID: 3704696 • 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 helper(keys):
key_dict = {}
key_len = len(keys[0])
for key in keys:
if len(key) != key_len:
return False
if key in key_dict:
return False
key_dict[key] = 1
return True
def is_valid_mapping(mapping):
keys = list(mapping.keys())
values = list(mapping.values())
if len(keys) == 0:
return True
return helper(keys) and helper(values)
print(is_valid_mapping({'a':'y', 'ab':'xx', 'b':'z'} ))
print(is_valid_mapping({'a':'yy', 'b':'xx', 'c':'zz'} ))
# copy pastable code link: https://paste.ee/p/XpEJs
Sample execution:
False
True
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.