Situation:
You are given a list of products sold in the store, and you want to purchase as many types of products as possible within your given budget (closest to given budget). Write function “maximize products(budget, product_list)” that takes a budget and a product list as input and returns a list of as many products that can be purchased as possible. The returned list should contain only the names of the products you are purchasing, and you should include as many varieties as possible without exceeding your budget.
Example Input: budget = 3000, product_list = [(“Apples”, 1000), (“Banana”, 500), (“Oranges”, 1500), (“Grapes”, 2000), (“Cherry”, 800)]
Example Output: [“Banana”, “Apple”, “Orange”]
I was able to include as many varieties as possible, but I am having trouble getting combination of products that costs closest to given budget. Please help…
def maximize_products(budget, product_list):
sorted_products = sorted(product_list, key=lambda x: x[1])
selected_products = []
total_cost = 0
for product, price in sorted_products:
if total_cost + price <= budget:
total_cost += price
selected_products.append(product)
else:
break
return selected_products
budget=int(input("budget: "))
product_list=[]
n = int(input("number of products: "))
for i in range(n):
name, price=input("Enter the product name and price (ex: apple 1000): ").split()
product_list.append((name, int(price)))
print(maximize_products(budget, product_list))
how can I add function that calculate and compare the sum of product prices??
yhc is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.