-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrod_cut.py
executable file
·81 lines (62 loc) · 1.84 KB
/
rod_cut.py
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/python
# vim: foldlevel=0
"""
Given a rod of length n inches and an array of prices that contains prices of all pieces
of size smaller than n. Determine the maximum value obtainable by cutting up the rod and
selling the pieces.
http://www.geeksforgeeks.org/dynamic-programming-set-13-cutting-a-rod/
"""
def recursive(values, length):
if length == 0:
return 0
max_value = 0
for i in range(length):
max_value = max(max_value, recursive(values, length-i-1) + values[i])
# Alternatively:
#return max(v + rec(length-l-1, values) for l, v in enumerate(values) if l+1 <= length)
return max_value
def solution1(values):
"""
Recursive solution.
>>> solution1([1, 5, 8, 9, 10, 17, 17, 20])
22
>>> solution1([3, 5, 8, 9, 10, 17, 17, 20])
24
"""
return recursive(values, len(values))
def dp(values, length, memo):
if length == 0:
return 0
if memo[length-1] == 0:
max_value = 0
for i in range(length):
max_value = max(max_value, dp(values, length-i-1, memo) + values[i])
memo[length-1] = max_value
return memo[length-1]
def solution2(values):
"""
Top-down dynamic programming.
>>> solution2([1, 5, 8, 9, 10, 17, 17, 20])
22
>>> solution2([3, 5, 8, 9, 10, 17, 17, 20])
24
"""
return dp(values, len(values), [0] * len(values))
def solution3(values):
"""
Bottom-up dynamic programming.
>>> solution3([1, 5, 8, 9, 10, 17, 17, 20])
22
>>> solution3([3, 5, 8, 9, 10, 17, 17, 20])
24
"""
memo = [0] * len(values)
for i in range(len(values)):
max_value = values[i]
for j in range(i):
max_value = max(max_value, memo[i-j-1] + values[j])
memo[i] = max_value
return memo[-1]
if __name__ == "__main__":
import doctest
doctest.testmod()