Skip to content

Update rod_cutting.py #995

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 13, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update rod_cutting.py
added doctests
  • Loading branch information
SandersLin authored Jul 10, 2019
commit a6f07ab08cbacdc304dd323a68042e459a1c0e92
24 changes: 8 additions & 16 deletions dynamic_programming/rod_cutting.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,19 @@
### SOLUTION ###
"""
Optimal Substructure:
When we receive a rod, we have two options:
a) Don't cut it and sell it as is (receiving prices[length])
b) Cut it and sell it in two parts. The length we cut it and the rod we are
left with, which we have to try and sell separately in an efficient way.
Choose the maximum price we can get.
"""

def rod_cutting_recursive(prices,length):
"""
Given a rod of length n and array of prices that indicate price at each length.
Determine the maximum value obtainable by cutting up the rod and selling the pieces

>>> rod_cutting_recursive([0,1,5,8,9],4)
10
>>> rod_cutting_recursive([0,1,1,1],3)
3

Args:
prices: list indicating price at each length, where prices[0] = 0 indicating rod of zero length has no value
prices: list indicating price at each length, where prices[0] = 0 indicating rod of zero length has no value
length: length of rod

Returns:
Maximum revenue attainable by cutting up the rod in any way.

Raises:
KeyError: Raises an exception.
"""
#base case
if length == 0:
Expand All @@ -34,7 +26,7 @@ def rod_cutting_recursive(prices,length):

def main():
assert rod_cutting_recursive([0,1,5,8,9,10,17,17,20,24,30],10) == 30

if __name__ == '__main__':
main()

Expand Down