gpt4 book ai didi

python - python 中的内存,一个错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:35:01 25 4
gpt4 key购买 nike

我目前正在上算法课。我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com