Python 3 Assume you have a variable , budget , that is associated with a positiv
ID: 648094 • Letter: P
Question
Python 3
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 .
Explanation / Answer
let the budget is 200$
>>> budget = 200 # 200 dollars >>> shoppinglist = ('ipod', 'books', 'dvds', 'cds', 'games', 'batteries') >>> price = {'ipod':75, 'books':50, 'dvds':35, 'cds':30, 'games':20, 'batteries':10} >>> def check(budget, shoppinglist, price): ... bought = [] ... for k in shoppinglist: ... if budget-price[k] >= 0: ... bought.append(k) ... budget-=price[k] ... else: ... return bought ... >>> print check(budget, shoppinglist, price) ['ipod', 'books', 'dvds', 'cds'] >>>
All the logic here is in the check() function. We loop over every item in shoppinglist, and if the current budget minus the price for that item is greater than or equal to 0, we append it to bought. Else, we return the list bought.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.