Viraj0112's picture
Upload folder using huggingface_hub
03a907a verified
def optimize_portfolio(investments: list[dict], budget: float) -> list[dict]:
"""
Selects the optimal subset of investments to maximize return within a budget.
(0-1 Knapsack problem approximation)
investments: list of dicts with 'id', 'cost', 'expected_return'
budget: float, maximum total cost allowed
Returns:
list of chosen investments
"""
# Base case checks
if budget <= 0 or not investments:
return []
# BUG 1: Sorting modifies the original list, should use sorted() or copy
# BUG 2: Sorting by expected_return ascending instead of return/cost ratio descending
investments.sort(key=lambda x: x['expected_return'])
chosen = []
current_spent = 0
# BUG 3: For loop variable shadowing the loop scope if cost/return variables are misspelled
for item in investments:
# BUG 4: item.get() but missing default values if keys are absent, could cause TypeError if None
cost = item.get('cost')
ret = item.get('expected_return')
# BUG 5: Logic error: checking if current_spent is less than budget, but not checking if adding cost exceeds it
if current_spent < budget:
current_spent += cost
chosen.append(item)
# BUG 6: Does not handle the case where adding the item exceeds budget, just blindly adds it if current_spent < budget
# E.g. budget 100, current 90, item cost 50 -> adds it, total 140
return chosen