Answer:
Here is the Python function:
def group_by(s, fn): #method definition
group = {} #dictionary
for e in s: #for each element from s
key = fn(e) #set key to fn(e)
if key in group: #if key is in dictionary group
group[key].append(e) #append e to the group[key]
else: #if key is not in group
group[key] = [e] #set group[key] to [e]
return group #returns dictionary group
Step-by-step explanation:
To check the working of the above function call the function by passing a sequence and a function and use print function to display the results produced by the function:
print(group_by([12, 23, 14, 45], lambda p: p // 10))
print(group_by(range(-3, 4), lambda x: x * x))
function group_by takes in a sequence s and a function fn as parameters. It then creates an empty dictionary group. The values of the dictionary are lists of elements from s. Each element e in a list is constructed such that fn(e) is the same for all elements in that list. Finally, the key for each value is fn(e). The function returns a dictionary. The screenshot of the program along with its output is attached.