Question

In: Computer Science

I need to modify the following code (using Python3), where Groceries.csv is of following form (Item...

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)))

Solutions

Expert Solution

Following are the steps to read the file and populate the productPrices dictionary.

  1. read the file using csv module reader method.
  2. loop through all the rows/lines read from the file
  3. insert the values in dictionary. first value is key and second is value

Following are the steps to calculate the final cost:

  1. loop through the shopping cart
  2. get the item quantity from item in shopping cart
  3. get the item price from productPrices dictionary using item name as key
  4. calculate the cost for that item by multiplying item quantity and item price
  5. add the result in 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:


Related Solutions

I need to reverse strings with spaces using the nextLine() with Scanner in the following code:...
I need to reverse strings with spaces using the nextLine() with Scanner in the following code: package Chapter8; //To import the necessary libraries import java.util.Scanner; public class BackwardString { public static void main(String[] args) { //To read string from user input String input; Scanner scanner = new Scanner(System.in); System.out.print("Enter String here : "); input=scanner.next(); //To reverse passed string backward(input); //To close Scanner object scanner.close(); } //To reverse the input string private static void backward(String source) { int i, len =...
I need the code in python where I can encrypt and decrypt any plaintext. For example,...
I need the code in python where I can encrypt and decrypt any plaintext. For example, the plaintext "hello" from each of these Block Cipher modes of Operation. Electronic Code Block Mode (ECB) Cipher block Mode (CBC) Cipher Feedback Mode (CFB) Output feedback Mode (OFB) Counter Mode (CTR) Here is an example, Affine cipher expressed in C. Encryption: char cipher(unsigned char block, char key) { return (key+11*block) } Decryption: char invcipher(unsigned char block, char key) { return (163*(block-key+256)) }
If there are 32 concurrent processes, how will you modify the following code? Process i do...
If there are 32 concurrent processes, how will you modify the following code? Process i do { while (turn == j);                critical section; turn = j;                remainder section } while (true);
look this code is a correct but i want modify it to allow the client to...
look this code is a correct but i want modify it to allow the client to have three attempts to login to the server package hw2; import java.net.*; import java.util.Formatter; import java.util.Random; import java.util.Scanner; import java.io.*; public class Client {    Socket server;    int port;    Formatter toNet = null;    Scanner fromNet = null;    Scanner fromUser = new Scanner(System.in);    public Client() {        try {            // login at server at local host...
How to validate Javascript form data? Here is the code. Can someone modify it so that...
How to validate Javascript form data? Here is the code. Can someone modify it so that all the information is validated? Thanks. <!DOCTYPE html> <html lang="en"> <head>    <title>Music Survey</title>    <meta charset="utf-8"> </head> <style>    legend { font-weight:bold;    }    </style> <body> <h1>Music Survey</h1> <form method="post" action=""> <label for="myname"><b>Name:</b></label>        <input type="text" name="myname" id="myname">        <br><br> <label for="myemail"><b>Email:</b></label>        <input type="email" name="myemail" id="myemail">        <br><br>   <fieldset> <legend>Select Your Favorite Types of Music:</legend> <input type="checkbox"...
Could you modify my code so it meets the following requirement? (Python Flask) I want the...
Could you modify my code so it meets the following requirement? (Python Flask) I want the user to register for account using email and password, then store that data into a text file. Then I want the data to be read when logging in allowing the user to go to home page. -------------Code-------------------- routes.py from flask import Flask, render_template, redirect, url_for, request, session import json, re app = Flask(__name__) '''@app.before_request def before_request(): if 'visited' not in session: return render_template("login.html") else:...
I need this in java using textpad. I am missing a few lines where I added...
I need this in java using textpad. I am missing a few lines where I added in comments. I don't know what I need to add in. Here are the two programs as pasteable code.The comments in the code say what I need done. The two programs are below. I need it to work with the generic version of SLLNode. It is posted at the bottom. public class ListDemoHw { public static void printLinkedList(SLLNode node) { // display all elements...
Please solve the following question by Python3. Code the function calc_tot_playtime to calculate the total playtime...
Please solve the following question by Python3. Code the function calc_tot_playtime to calculate the total playtime by user and game. Each element in input is of the format "user_id, game_id, total_playtime_in_minute". Input is a list of strings of the above format. Output should be sorted by user_id, game_id in ascending order. Example: Input: ["1,10,20", "1,15,10m", "1,10,10m", "2,10,40m", "2, 20, 10m"] output: [('1', '10', 30), ('1', '15', 10), ('2', '10', 40), ('2', '20', 10)] Functions are defined below: def calc_total_playtime(input_data=None): """...
I need a full java code. And I need it in GUI With the mathematics you...
I need a full java code. And I need it in GUI With the mathematics you have studied so far in your education you have worked with polynomials. Polynomials are used to describe curves of various types; people use them in the real world to graph curves. For example, roller coaster designers may use polynomials to describe the curves in their rides. Polynomials appear in many areas of mathematics and science. Write a program which finds an approximate solution to...
this is a python code that i need to covert to C++ code...is this possible? if...
this is a python code that i need to covert to C++ code...is this possible? if so, can you please convert this pythin code to C++? def main(): endProgram = 'no' print while endProgram == 'no': print # declare variables notGreenCost = [0] * 12 goneGreenCost = [0] * 12 savings = [0] * 12 months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] getNotGreen(notGreenCost, months) getGoneGreen(goneGreenCost, months) energySaved(notGreenCost, goneGreenCost, savings) displayInfo(notGreenCost, goneGreenCost, savings, months)...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT