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

Python Question!!!! The aim of this exercise is to use a price list to calculate

ID: 671646 • Letter: P

Question

Python Question!!!!

The aim of this exercise is to use a price list to calculate the average bill amount from a history of purchases by different customers.

You are given a price list in the form of a list of 2-element tuples, where each tuple corresponds to a different product. The first element in each tuple is a string corresponding to the name of the product, e.g., "bread". The second element in each tuple is the cost of the product as a float, e.g., 3.00 for $3.00. For example, the list [('milk', 4.00), ('eggs', 5.00), ('tofu', 3.00)] specifies the prices of a carton of milk, a carton of eggs, and a package of tofu.

You are also given a list of shopping bills, where each bill is a list of products that have been bought by a customer on a visit to your store. For example, the list [['milk','eggs'],['milk','milk','milk','tofu'], ['eggs','milk','tofu']]corresponds to three separate bills: a customer who bought one carton of milk and one carton of eggs, a customer who bought three cartons of milk and one package of tofu, and a customer who bought one carton of eggs, one carton of milk and a package of tofu.

You can assume that all inputs are of the correct type, that each product appears only once in the price list, and that every product in the list of shopping bills appears in the price list.

Your goal is to write a function that calculates the total amount of each bill, and returns the average amount per bill. For example, the average amount of the list of bills given above is

Thus, your function would return 12.00.

You should write a function averageBill(prices, bills) that takes a price list prices and a list of shopping bills bills and returns the float value of the average amount per bill.

Example calls to the function are:

>>> print(averageBill([('milk',4.00),('eggs',5.00),('tofu',3.00)], [['milk','eggs'],['milk','milk','milk','tofu'],['eggs','milk','tofu']]))
12.0
>>> print(averageBill([('milk',4.00),('eggs',5.00),('tofu',3.00)], [['eggs','eggs']]))
10.0
>>> print(averageBill([('bread',3.00),('vegemite',4.20)], [['vegemite','bread'],['bread','vegemite']]))
7.2
>>> print(averageBill([('spam',1.00),('chocolate',4.87)], [['spam'],['spam','spam'],['spam','spam','spam']]))
2.0

Explanation / Answer

def averageBill(productPrice,bills):
sum_ = 0
price = {}
for product in productPrice:
price[product[0]] = product[1]
  
  
for bill in bills:
for item in bill:
sum_ = sum_ + price[item]
  
return sum_/len(bills)
  
  
print(averageBill([('milk',4.00),('eggs',5.00),('tofu',3.00)], [['milk','eggs'],['milk','milk','milk','tofu'],['eggs','milk','tofu']]))