MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / naive_cut_rod_recursive

Function naive_cut_rod_recursive

dynamic_programming/rod_cutting.py:14–53  ·  view source on GitHub ↗

Solves the rod-cutting problem via naively without using the benefit of dynamic programming. The results is the same sub-problems are solved several times leading to an exponential runtime Runtime: O(2^n) Arguments --------- * `n`: int, the length of the rod * `pr

(n: int, prices: list)

Source from the content-addressed store, hash-verified

12
13
14def naive_cut_rod_recursive(n: int, prices: list):
15 """
16 Solves the rod-cutting problem via naively without using the benefit of dynamic
17 programming. The results is the same sub-problems are solved several times
18 leading to an exponential runtime
19
20 Runtime: O(2^n)
21
22 Arguments
23 ---------
24
25 * `n`: int, the length of the rod
26 * `prices`: list, the prices for each piece of rod. ``p[i-i]`` is the
27 price for a rod of length ``i``
28
29 Returns
30 -------
31
32 The maximum revenue obtainable for a rod of length `n` given the list of prices
33 for each piece.
34
35 Examples
36 --------
37
38 >>> naive_cut_rod_recursive(4, [1, 5, 8, 9])
39 10
40 >>> naive_cut_rod_recursive(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30])
41 30
42 """
43
44 _enforce_args(n, prices)
45 if n == 0:
46 return 0
47 max_revue = float("-inf")
48 for i in range(1, n + 1):
49 max_revue = max(
50 max_revue, prices[i - 1] + naive_cut_rod_recursive(n - i, prices)
51 )
52
53 return max_revue
54
55
56def top_down_cut_rod(n: int, prices: list):

Callers 1

mainFunction · 0.85

Calls 1

_enforce_argsFunction · 0.85

Tested by

no test coverage detected