In: Computer Science
Assume you have a variable, budget, that is associated with a positive integer. Assume you have another variable, shopping_list, that is a tuple of strings representing items to purchase in order of priority. (For example: ("codelab", "textbook", "ipod", "cd", "bike")) Furthermore, assume you have a variable, prices that is a dictionary that maps items (strings such as those in your shopping_list) to positive integers that are the prices of the items. Write the necessary code to determine the number of items you can purchase, given the value associated with budget, and given that you will buy items in the order that they appear in the tuple associated with shopping_list. Associate the number of items that can be bought with the variable number_of_items.
In Python
Here is the code:
budget = 50
prices={'codelab':25, 'textbook':20, 'ipad':15, 'cd':5}
shopping_list = ('codelab', 'textbook', 'ipad', 'cd')
number_of_items = 0
for item in shopping_list:
if(budget
else:
number_of_items = number_of_items + 1
budget = budget - prices[item]
if(number_of_items==len(shopping_list)):
print('All', len(shopping_list), 'items can be purchased')
else:
print('Only', number_of_items, 'items can be purchased')
Output: