diff options
| author | mo khan <mo@mokhan.ca> | 2021-11-21 18:07:39 -0700 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2021-11-21 18:07:39 -0700 |
| commit | 28bb5a9343eb4d747fc17487e38c093ba9760885 (patch) | |
| tree | 12012ca2973ee4ac22c4e8043f7dff222529be0c /exercises/15.1 | |
| parent | e1316a4ac1aa7726336b3a07eeef25de8290e6c6 (diff) | |
top down dp solution in python
Diffstat (limited to 'exercises/15.1')
| -rw-r--r-- | exercises/15.1/rod_cutting.py | 21 |
1 files changed, 21 insertions, 0 deletions
diff --git a/exercises/15.1/rod_cutting.py b/exercises/15.1/rod_cutting.py index ec24930..8c67394 100644 --- a/exercises/15.1/rod_cutting.py +++ b/exercises/15.1/rod_cutting.py @@ -8,6 +8,23 @@ def cutRod(p, n): q = max(q, p[i] + cutRod(p, n-i)) return q +def topDownCutRodAux(p, n, r): + if n == 0: + return 0 + if r[n] >= 0: + return r[n] + q = -1 + for i in range(1, n+1): + q = max(q, p[i] + topDownCutRodAux(p, n-i, r)) + r[n] = q + return q + +def topDownCutRod(p, n): + r = [] + for i in range(n+1): + r.append(-1) + return topDownCutRodAux(p, n, r) + class TestRodCutting(unittest.TestCase): def setUp(self): self.p = [0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30] @@ -17,5 +34,9 @@ class TestRodCutting(unittest.TestCase): for n in range(10): self.assertEqual(self.r[n], cutRod(self.p, n)) + def test_top_down(self): + for n in range(10): + self.assertEqual(self.r[n], topDownCutRod(self.p, n)) + if __name__ == '__main__': unittest.main() |
