Your goal is to write a Python function that finds the product that occurs most
ID: 670748 • Letter: Y
Question
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 Python 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
def remove_duplicates(values):
output = []
seen = set()
for value in values:
# If value has not been encountered yet,
# ... add it to both list and set.
if value not in seen:
output.append(value)
seen.add(value)
return output
def getValue(products,count):
products = remove_duplicates(products)
for product in products:
if(count.has_key(product)):
count[product] = count[product]+1
else:
count[product] = 1
def mostPopular(bills):
count = {}
max_ = 0
product = []
for bill in bills:
getValue(bill,count)
for key in count.keys():
if count[key]>max_:
max_ = count[key]
for key in count.keys():
if count[key] == max_:
product.append(key)
return product
print(mostPopular([['milk','eggs'],['milk','milk','milk','tofu'],['eggs','milk','tofu']]))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.