I’m currently taking an algorithms class. I’m testing a lot of them out in python, including dynamic programming. Here is an implementation of the bottom up rod cutting implementation.
It doesn’t work because of the off-by-one error. Is there a global setting in python where I can change the default array index to be 1 and not 0? Or can someone please provide me with a better strategy for over-coming the off-by-one errors, which I encounter a million times. It’s super annoying.
def bottom_up_memo_cut_rod(p,n):
r = [ 0 for i in range(n) ]
r[0] = 0
for j in range(n):
q = -1
for i in range(j):
q = max(q, p[i] + r[j-i])
r[j] = q
return r[n]
bottom_up_memo_cut_rod([1,5,8,9], 4)
answer should be 10 in this case cutting 4 into (2,2) yields the max price of 10.
There are a couple of things in Python that may help you. The built-in
enumerateis a great one.You can also use list slicing with enumerate to shift indices if absolutely necessary:
Realistically though, you don’t want to try to change the interpreter so that lists start at index 1. You want to adjust your algorithm to work with the language.