Python Question!!!! The aim of this exercise is to find the product(s) that is/a
ID: 671645 • Letter: P
Question
Python 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, in the same format as Question 1. You can assume that all inputs are of the correct type.
Your goal is to write a 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:
>>> print(mostPopular([['milk','eggs'],['milk','milk','milk','tofu'],['eggs','milk','tofu']]))
['milk']
>>> print(mostPopular([['milk','eggs'],['milk','milk','tofu','eggs'],['eggs']]))
['eggs', 'milk']
>>> print(mostPopular([['milk','eggs'],['milk','milk','tofu','eggs'],[]]))
['milk']
>>> print(mostPopular([['milk'],['eggs']]))
['eggs', 'milk']
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.