File size: 1,546 Bytes
03a907a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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