Question: PLEASEE HELP!!Already posted twice but wrong answer?? Pleasee help implement BACKTRACKING so that I can store a list of items to sell in O(N+P) space
PLEASEE HELP!!Already posted twice but wrong answer?? Pleasee help implement BACKTRACKING so that I can store a list of items to sell in O(N+P) space complexity where P is price limit??
I got this list of list-[['0', 'Cool Blue Marella Jug', '33', '15'], ['1', 'Weight Loss Pack', '55', '16'], ['2', 'Natural Black Vogue Lashes', '10', '6'], ['3', 'Paris Age Perfect Intense Nutrition Serum', '45', '22']] the first number is the product id, the second number (55,10,...) is the price and the third number (16,6...)is the profit.Using my code below, if I enter a price limit I should get the highest profit by best combinations of items(items can be sold more than once).BUT now I need to modify this so that it aALSO returns a list, chosenProduct, representing the chosen product ID to be sold.
E.g. If products cool blue marella jug were chosen twice and weight loss pack chosen once the list should be ,chosenProduct=[0,0,1]
I tried storing the product chosen in a list whenever I found a new optimum but it stores every optimum it finds from value 1 to price_limit? I want it to store ONLY the latest product chosen and use backtracking from there to list all product chosen that make up the profit?This is my code.
def dp_pricelimit(product_list, price_limit): #to store results chosenProduct=[0]*(price_limit+1) memo=[0]*(price_limit+1) memo[0]=0 for price in range(1, price_limit+1): for item in product_list:#go through the items if item[2]<=price: balance=price-item[2] profit=item[3] + memo[balance] if profit>memo[price]:#if found new optimal memo[price]=profit chosenProduct[price]=item[0]
return memo[price_limit],chosenProduct
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
