【问题标题】:Dynamic programming python implementation problem动态编程python实现问题
【发布时间】:2020-01-01 13:41:20
【问题描述】:

我正在尝试使用反向迭代来实现动态编程代码。但是,python for 循环给了我列表超出范围的错误。

pi = [65,61,42,35,30,32,38,42,53,57,59,64,72,77,64,62,40,64,55,43,40,55,30,21]

#backward recursion
#number of stages T
T = [i for i in range(1,25)]
#possible states
S = [i for i in range(100,1100,100)]
#decision variable
D = [100,-100,0]

#initilaize the value function
obj_val = [[[0 for i in range(1,25)] for j in range(1,9)] for k in range(1,4)]

for t in range(24,0,-1):  #Step backward through problem stages T
    for s in range(9): #Step through each possible stage t state
        for d in range(4):     #step through each feasible stage t decision D
             if t == 24:  #if it is the last stage
                 obj_val[t][s][d] = pi[t]*D[d]
             else: 
                 obj_val[t][s][d] = pi[t]*D[d]+obj_val[t+1][s][d]

IndexError: 列表索引超出范围(对于 if 和 else 条件)

【问题讨论】:

  • 只是猜测,pi 中有 24 项?现在,看看obj_val[t+1]
  • 我稍微修改了代码。由于我正在执行反向递归,因此对于最终值以外的 t 值,它应该能够访问先前计算的值。此外,错误适用于 if 和 else 条件。
  • 完全不相关,但T = [i for i in range(1,25)] 是一种相当复杂(可能效率较低)的写T = list(range(1, 25))的方式

标签: python dynamic-programming


【解决方案1】:

obj_val中,最外部的数组只有4个对象。所以当if 为真时,你无法得到obj_val[24]。 此外,您的任何数组中都没有索引 24。最高可达 23。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-27
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 2015-07-18
    • 1970-01-01
    • 2016-02-09
    相关资源
    最近更新 更多