In: Computer Science
Magnolia resident’s association registers who holds different positions in a text variable MA.
PS: Remember that triple quotation marks """…""" is used for texts that go over several lines.
MA= \
"""
Magnolia resident’s association
leader: Kathy
cashier: Jack
IT guy: Richard
parking manager: Kathy
event manager: Richard
maintenance manager: Kathy
fire safety manager: Kathy
"""
Develop a function which returns the list over the positions a person holds.
>>> position(«Richard»)
[«IT guy», «event manager»]
Find the python code below. I have written comments for every line. Also, you can find a sample output screenshot at the end of the answer.
# given string
MA= \
"""
Magnolia resident’s association
leader: Kathy
cashier: Jack
IT guy: Richard
parking manager: Kathy
event manager: Richard
maintenance manager: Kathy
fire safety manager: Kathy
"""
# define function
def position(x):
# split the string into an array by new line character
registers = MA.split("\n")
# Discard lines which do not contain a ":" (position: name format should be followed)
registers = [i for i in registers if ":" in i]
# declaring a dictionary, key = name, value = array of positions
d = dict()
# iterate over the registers array, split by ": " and add to dictionary
for i in registers:
i = i.split(": ")
if i[1] in d: # name in dictionary
d[i[1]].append(i[0])
else: # name not in dictionary
d[i[1]] = [i[0]]
return d[x]
# invoke function
print(position("Richard"))
Thanks & Regards.