summaryrefslogtreecommitdiff
path: root/exercises/15.1/rod_cutting.py
blob: 7d7609c1e673f2bb665ca575988be2ea2f18853a (plain)
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import unittest

def cutRod(p, n):
    if n == 0:
        return 0
    q = -1
    for i in range(1, n+1):
        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)

def bottomUpCutRod(p, n):
    if n == 0:
        return 0
    r = [0]
    for i in range(1, n+1):
        r.append(-1)
    for j in range(1, n+1):
        q = -1
        for i in range(1, j+1):
            q = max(q, p[i] + r[j-i])
        r[j] = q

    return r[n]

class TestRodCutting(unittest.TestCase):
    def setUp(self):
        self.p = [0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30]
        self.r = [0, 1, 5, 8, 10, 13, 17, 18, 22, 25, 30]

    def test_recursive(self):
        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))

    def test_bottom_up(self):
        for n in range(10):
            self.assertEqual(self.r[n], bottomUpCutRod(self.p, n))

if __name__ == '__main__':
    unittest.main()