Screen Link:
I was surprised to see that the provided solution uses Sets, which have not been taught at this point in the curriculum. Here is my initial solution, without sets:
# Aux. method: computes the average bill or tip or size for a list of rows
def get_avgs(dic, col, indices):
inner_dic = dic[col]
total = 0
for index in indices:
total += inner_dic[index]
return total / len(indices)
# Main method
def avg_group(dic, col): # col is either 'sex', or 'smoker', or 'size'
inner_dic = dic[col] # contains the values for the column
result_dic = {} # this is the end-goal result of the method
# Extract the keys of the result dictionary from the values in the column
for index, value in inner_dic.items():
if value not in result_dic:
result_dic[value] = []
# Calculate the 3 averages for each key, and add them as values
for key, averages in result_dic.items():
relevant_indices = [] # the rows needed to calculate the averages
for index, value in inner_dic.items():
if value == key:
relevant_indices.append(index)
averages.append(get_avgs(dic, 'total_bill', relevant_indices))
averages.append(get_avgs(dic, 'tip', relevant_indices))
averages.append(get_avgs(dic, 'size', relevant_indices))
return result_dic
Sets make it easy to sort the keys in the end-result dictionary. In my solution, the keys are not sorted (it still passes the submission test since dictionaries are intrinsically unordered).
My outcome:
print(avg_group(d, "sex"))
{'Male': [23.24, 2.373333333333333, 2.6666666666666665], 'Female': [19.705, 2.245, 2.0]}
Outcome of solution with sets:
print(avg_group(d, "sex"))
{'Female': [19.705, 2.245, 2.0], 'Male': [23.24, 2.373333333333333, 2.6666666666666665]}
But sets are not taught in the Python Fundamentals course, and are only introduced in the series of practice problems that follows this problem. So how come they are already used in the solution to this problem? I wish there was at least a hint… could have saved myself a one hour long headache.