In: Computer Science
I need to modify the following code (using Python3), where Groceries.csv is of following form (Item on 1st column, price on 2nd)
Stewing beef,15.45 Ground beef,11.29 Pork chops,11.72 Chicken,7.29 Bacon,7.12 Wieners,4.33 Canned salmon,5.68 Homogenized milk,5.79 Partly skimmed milk,5.20 Butter,4.99 Processed cheese slices,2.53 Evaporated milk,1.89 Eggs,3.11 Bread,2.74 Soda crackers,3.27 Macaroni,1.45 Flour,4.54 Corn flakes,5.72 Apples,4.71 Bananas,1.56 Oranges,3.70 ...
a. In the function createPricesDict(), create a dictionary of each product mapped to its price.
b. Suppose we have another dictionary for our cart items, mapping each product to its quantity. Complete the function calculateShoppingCost() to get this dictionary as well as the dictionary created in the previous step and return the total amount that the customer owes.
=======
import csv def calculateShoppingCost(productPrices, shoppingCart): finalCost = 0 "*** Add your code in here ***" return finalCost def createPricesDict(filename): productPrice = {} "*** Add your code in here ***" return productPrice if __name__ == '__main__': prices = createPricesDict("Grocery.csv") myCart = {"Bacon": 2, "Homogenized milk": 1, "Eggs": 5} print("The final cost for our shopping cart is {}".format(calculateShoppingCost(prices, myCart)))
Following are the steps to read the file and populate the productPrices dictionary.
Following are the steps to calculate the final cost:
Please refer the screenshot for indentation.
Code:
import csv
def calculateShoppingCost(productPrices, shoppingCart):
finalCost = 0
""" loop through shoppingCart item by item """
for item in shoppingCart.items():
""" calculate cost for the current item and add it in finalCost
"""
""" item quanitity """
itemQuantity = item[1]
""" get the item price from productPrices dictionary """
itemPrice = productPrices[item[0]]
""" multiple item quantity with item price and add the result in
final cost """
finalCost = finalCost + itemQuantity * itemPrice
""" return the final cost """
return finalCost
def createPricesDict(filename):
productPrice = {}
""" open csv file in read mode """
with open(filename,'rt')as file:
"""
read the file content using csv module reader method
and get the list of all columns per line or row in the file
"""
productDetails = csv.reader(file)
""" loop through all the product detail lines read from the file
"""
for product in productDetails:
"""
first element in list is first column in csv file that is product
name.
second element is the price of the product.
Add the product name as key and price as value in dictionary.
"""
productPrice[product[0]] = float(product[1])
""" return the productPrices dictionary """
return productPrice
if __name__ == '__main__':
prices = createPricesDict("Grocery.csv")
myCart = {"Bacon": 2,
"Homogenized milk": 1,
"Eggs": 5}
print("The final cost for our shopping cart is
{}".format(calculateShoppingCost(prices, myCart)))
Output: