|
| 1 | +import unittest |
| 2 | +from typing import List |
| 3 | +from robber import Solution |
| 4 | + |
| 5 | +class TestHouseRobber(unittest.TestCase): |
| 6 | + |
| 7 | + def test_example1(self): |
| 8 | + self.assertEqual(Solution().rob([1,2,3,1]), 4) |
| 9 | + |
| 10 | + def test_example2(self): |
| 11 | + self.assertEqual(Solution().rob([2,7,9,3,1]), 12) |
| 12 | + |
| 13 | + def test_single_element(self): |
| 14 | + self.assertEqual(Solution().rob([5]), 5) |
| 15 | + |
| 16 | + def test_two_elements(self): |
| 17 | + self.assertEqual(Solution().rob([2,1]), 2) |
| 18 | + self.assertEqual(Solution().rob([1,2]), 2) |
| 19 | + |
| 20 | + def test_all_zeroes(self): |
| 21 | + self.assertEqual(Solution().rob([0,0,0,0]), 0) |
| 22 | + |
| 23 | + def test_strictly_increasing(self): |
| 24 | + # [1,2,3,4,5] → choose 1 + 3 + 5 = 9 |
| 25 | + self.assertEqual(Solution().rob([1,2,3,4,5]), 9) |
| 26 | + |
| 27 | + def test_uniform_values(self): |
| 28 | + # [5,5,5,5,5] → 5+5+5 = 15 |
| 29 | + self.assertEqual(Solution().rob([5,5,5,5,5]), 15) |
| 30 | + |
| 31 | + def test_large_input(self): |
| 32 | + arr = [400]*100 |
| 33 | + # best = sum of every second: 50 * 400 = 20000 |
| 34 | + self.assertEqual(Solution().rob(arr), 20000) |
| 35 | + |
| 36 | + # A brute-force solver for validation |
| 37 | + def brute(self, nums): |
| 38 | + from functools import lru_cache |
| 39 | + @lru_cache(None) |
| 40 | + def dfs(i): |
| 41 | + if i >= len(nums): |
| 42 | + return 0 |
| 43 | + return max(nums[i] + dfs(i+2), dfs(i+1)) |
| 44 | + return dfs(0) |
| 45 | + |
| 46 | + def test_random_small(self): |
| 47 | + import random |
| 48 | + for _ in range(30): |
| 49 | + n = random.randint(1, 8) |
| 50 | + arr = [random.randint(0, 20) for _ in range(n)] |
| 51 | + self.assertEqual(Solution().rob(arr), self.brute(tuple(arr))) |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == "__main__": |
| 55 | + unittest.main() |
0 commit comments