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

Need to modify the below code to return the time in minutes instead of seconds. (Using...
Need to modify the below code to return the time in minutes instead of seconds. (Using Python 2.7.6 ) def numberPossiblePasswords(numDigits, numPossiblePerDigit):     numPasswords = numPossiblePerDigit**numDigits     return numPasswords def maxSecondsToCrack(numPossiblePasswords, secPerAttempt):     time = numPossiblePasswords*secPerAttempt     return time nd = int(input("How many digits long is the passcode? "))       nc = int(input("How many possible characters are there per digit? ")) secondsPerAttempt = .08 npp = numberPossiblePasswords(nd, nc) totalSeconds = maxSecondsToCrack(npp, secondsPerAttempt) print("It will take you " + str(totalSeconds) + "...
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);
I need assistance with using Verilog to code the following: The decoder needs attention. Its function...
I need assistance with using Verilog to code the following: The decoder needs attention. Its function is to take the 10‐bit input, and give three 4‐bit signals. The first 4‐bit signal should be the number of hundreds, the second 4‐bit signal should be the number of tens, and the final 4‐bit signal should be the number of units. In Verilog, these can be calculated simply using the numerical operators, specifically: Divide (/)  Modulus(%) Given: input[9:0] number reg[3:0] numb_bcd0, numb_bcd1, numb_bcd2;   ...
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";...
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...
I need to make changes to code following the steps below. The code that needs to...
I need to make changes to code following the steps below. The code that needs to be modified is below the steps. Thank you. 1. Refactor Base Weapon class: a.            Remove the Weapon abstract class and create a new Interface class named WeaponInterface. b.            Add a public method fireWeapon() that returns void and takes no arguments. c.             Add a public method fireWeapon() that returns void and takes a power argument as an integer type. d.            Add a public method activate()...
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"...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT