Spaces:
Running
Running
| import pytest | |
| from dataset.problem_23.buggy import optimize_portfolio | |
| def test_optimize_portfolio(): | |
| investments = [ | |
| {'id': 'A', 'cost': 50, 'expected_return': 60}, # ratio 1.2 | |
| {'id': 'B', 'cost': 30, 'expected_return': 45}, # ratio 1.5 | |
| {'id': 'C', 'cost': 20, 'expected_return': 40}, # ratio 2.0 | |
| {'id': 'D', 'cost': 40, 'expected_return': 50}, # ratio 1.25 | |
| {'id': 'E', 'cost': 10, 'expected_return': 15} # ratio 1.5 | |
| ] | |
| # Original list should not be mutated | |
| orig_investments = [dict(i) for i in investments] | |
| # Budget 50 | |
| # Expected greedy: C (20) -> B (30) -> total cost 50, return 85 | |
| result = optimize_portfolio(investments, 50) | |
| assert investments == orig_investments, "Original list was mutated" | |
| # Assert correct items selected | |
| chosen_ids = {item['id'] for item in result} | |
| assert chosen_ids == {'B', 'C'}, f"Expected B and C, got {chosen_ids}" | |
| total_cost = sum(item['cost'] for item in result) | |
| assert total_cost <= 50 | |
| def test_budget_exceeded_check(): | |
| investments = [ | |
| {'id': 'A', 'cost': 90, 'expected_return': 100}, | |
| {'id': 'B', 'cost': 50, 'expected_return': 60} | |
| ] | |
| # Budget 100 | |
| # Expected: A (cost 90) | |
| result = optimize_portfolio(investments, 100) | |
| chosen_ids = {item['id'] for item in result} | |
| assert chosen_ids == {'A'}, "Should not include B since total cost would be 140" | |
| def test_empty_or_zero_budget(): | |
| assert optimize_portfolio([], 100) == [] | |
| assert optimize_portfolio([{'id': 'A', 'cost': 10, 'expected_return': 20}], 0) == [] | |