I\'m using Python language and the Pycharm program. Here\'s the question: Write
ID: 3816562 • Letter: I
Question
I'm using Python language and the Pycharm program. Here's the question:
Write the function shopping() that takes two arguments: a dictionary that maps store products to prices (i.e., the keys are product names – strings – and the values are the prices – integers), and a list of products that a person wants to buy. The list might contain products not for sale at the store. The function uses the dictionary and list to compute how much the shopping trip will cost.
As an example, suppose the dictionary products is defined as:
{’toothbrush’: 2, ’comb’: 3, ’soap’: 5, ’brush’: 7, ’shampoo’: 10}
and the list shopping list is defined as:
[’shampoo’, ’brush’, ’shampoo’, ’soap’, ’soap’, ’dog food’, ’soap’]
For these inputs,shopping(products, shoppinglist)would return 42.Note that the item“dogfood” is not for sale at the store, yet the function still is able to compute and return the total without crashing. Also note that shampoo was purchased twice and soap was purchased three times, which is reflected in the total cost.
Here are some additional tests:
products = {'shampoo': 10, 'soap': 5, 'comb': 3, 'brush': 7, 'toothbrush': 2}
print('For the following Part 2 tests, products is defined as:')
print(' ' + str(products))
shopping_list = ['shampoo', 'brush', 'shampoo', 'soap', 'soap', 'dog food', 'soap']
print('Testing shopping() for shopping_list = ' + str(shopping_list) + ' ' +
' Result: ' + str(shopping(products, shopping_list)))
shopping_list = ['candy', 'brush', 'brush', 'soap', 'fruit', 'soap']
print('Testing shopping() for shopping_list = ' + str(shopping_list) + ' ' +
' Result: ' + str(shopping(products, shopping_list)))
shopping_list = ['wood', 'paint', 'shovel', 'mop']
print('Testing shopping() for shopping_list = ' + str(shopping_list) + ' ' +
' Result: ' + str(shopping(products, shopping_list)))
Explanation / Answer
def shopping(products, shopping_list):
total_cost = 0
for item in shopping_list:
if item in products:
total_cost = total_cost + products[item]
return total_cost
products = {'toothbrush': 2, 'comb': 3, 'soap': 5, 'brush': 7, 'shampoo': 10}
shopping_list = ['shampoo', 'brush', 'shampoo', 'soap', 'soap', 'dog food', 'soap']
print shopping(products, shopping_list)