我目前正在学习算法类(class)。我正在用 python 测试其中的很多内容,包括动态编程。这是自下而上的杆切割实现的实现。
由于差一错误,它不起作用。 python 中是否有一个全局设置,我可以将默认数组索引更改为 1 而不是 0?或者有人可以为我提供一个更好的策略来克服我遇到过一百万次的相差一错误。真是太烦人了。
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)
答案应该是 10,在这种情况下,将 4 切入 (2,2) 会得到最大价格 10。
最佳答案
Python 中有一些东西可能对您有帮助。内置的 enumerate
是一个很棒的函数。
for idx, val_at_idx in enumerate(aList):
# idx is the 0-indexed position, val_at_idx is the actual value.
如果绝对必要,您还可以使用列表切片和枚举来移动索引:
for idxOffBy1, val_at_wrong_idx in enumerate(aList[1:]):
# idx here will be 0, but the value will be be from position 1 in the original list.
但实际上,您不想尝试更改解释器以使列表从索引 1 开始。您希望调整算法以使用该语言。
关于python - python 中的记忆化,有一个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13092172/