79.5k views
1 vote
Write a function that takes in a sequence s and a function fn and returns a dictionary. The values of the dictionary are lists of elements from s. Each element e in a list should be constructed such that fn(e) is the same for all elements in that list. Finally, the key for each value should be fn(e)

def group_by(s, fn):
""" >>> group_by([12, 23, 14, 45], lambda p: p // 10)
{1: [12, 14], 2: [23], 4: [45]}
>>> group_by(range(-3, 4), lambda x: x * x)
{0: [0], 1: [-1, 1], 4: [-2, 2], 9: [-3, 3]}
"""
Use Python

User Thllbrg
by
5.7k points

1 Answer

4 votes

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.

Write a function that takes in a sequence s and a function fn and returns a dictionary-example-1
User VinSmile
by
5.9k points