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 this code in C++ form using visual studios please: Create a class that simulates...
I need this code in C++ form using visual studios please: Create a class that simulates an alarm clock. In this class you should: •       Store time in hours, minutes, and seconds. Note if time is AM or PM. (Hint: You should have separate private members for the alarm and the clock. Do not forget to have a character variable representing AM or PM.) •       Initialize the clock to a specified time. •       Allow the clock to increment to the...
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...
Modify the code so that it provides a web form to collect the cookie values from...
Modify the code so that it provides a web form to collect the cookie values from the users. In other words, you will add two text boxes where users will enter the cookie name and the cookie value. You will also add a submit button, which lets users to send the cookie values to the server. The page should display the previous cookie values when it is loaded. <!DOCTYPE html> <?php     $cookie_name = "user";     $cookie_value = "John Doe";...
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"...
For the following code I need to open the file of a persons choice which I...
For the following code I need to open the file of a persons choice which I did. I can get it to read the file, but I need help with counting lines and characters feel like i have the code I just cant make it work. Either way, the program should then ask the user Analyze another file (y/n)? and repeat the process again (asking for a file and analyzing its meta-data). This should continue repeating until the user chooses...
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...
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. public class ListDemoHw { public static void printLinkedList(SLLNode node) { // display all elements in the linked list while(node != null) { System.out.print(node.info + " "); node = node.next; // move...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT