Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The aim of this exercise is to find the product(s) that is/are most popular in t

ID: 671341 • Letter: T

Question

The aim of this exercise is to find the product(s) that is/are most popular in the history of purchases by different customers.

You are given a list of shopping bills. You can assume that all inputs are of the correct type.

Your goal is to write a Python function that finds the product that occurs most frequently across all the given bills. Thus, your function would return ['milk'] given the list of bills [['milk','eggs'],['milk','milk','tofu'], ['eggs']]. In this case, 'milk'appeared 3 times, while 'eggs' appeared twice, and 'tofu'appeared once.

You should write a function mostPopular(bills) that takes a list of shopping bills bills and returns the list of products that are most frequent. If there are two or more products that have the highest frequency, then the products in the returned list should be in alphabetical order. If you are given an empty list of bills, you should return the empty list.

Example calls to the function are:

Explanation / Answer

import itertools import operator def most_common(L): # get an iterable of (item, iterable) pairs SL = sorted((x, i) for i, x in enumerate(L)) # print 'SL:', SL groups = itertools.groupby(SL, key=operator.itemgetter(0)) # auxiliary function to get "quality" for an item def _auxfun(g): item, iterable = g count = 0 min_index = len(L) for _, where in iterable: count += 1 min_index = min(min_index, where) # print 'item %r, count %r, minind %r' % (item, count, min_index) return count, -min_index # pick the highest-count/earliest item return max(groups, key=_auxfun)[0]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote