Can someone tell me where I have the error?

1
def asignacion_paquetes(U,m,v):
    P={}
    for u in range(U+1):
        P[0,u] =0
    for i in range(1,len(m)+1):
        P[i,0]=0
        for u in range(1,U+1):
            P[i,u] = max(P[i-1, u-x]+v[i,x] for x in range(0,min(u,m[i])+1))

    return P[len(m),U]

I would like to know where the error is because it tells me IndexError: list index out of range in the line where I put the arrow - > This code represents an optimization problem of optimal allocation of resources resolved by dynamic programming U represents the total resources and m is a list that represents the limit of resources that can be assigned to an activity i and v is a dictionary that has as key a tuple i , u that represents the benefit of assigning a resource or an activity i. All this with the aim of obtaining the greatest benefit. Hence the formula P[i,u]= max(P[i-1,u-x] + v[i,x] .

Can someone help me?

U = 12

m = [2,4,2,4,2]

v=dict(((i,u),randrange(100)) for i in range(1,len(m)+1) for u in range(0, U+1))

These are the values of the parameters

    
asked by Ada Leon 06.11.2017 в 16:35
source

1 answer

0

You have a problem with it using range() , I do not know if you know that in Python the indexes of any data collection start in 0 and the upper limit of range() is not inclusive. Specifically, the error is in the for deeper:

for i in range(1,len(m)+1):
    P[i,0]=0
    for u in range(1,U+1):
        P[i,u] = max(P[i-1, u-x]+v[i,x] for x in range(0,min(u,m[i])+1))

The first for iterates from i=1 to the length of m , with the dictionaries you have no problem, the problem you have when you do m[i] , as m is a list whose indexes begin in 0 , and you move the same 1 value plus the last index of the iteration does not exist hence the error. You should in any case do m[i-1] .

Some extra comments:

  • I would handle the keys of the dictionaries with the same scheme of the indexes of the lists where 0 is the first element, this would make the code more consistent
  • Also to make it clearer, when defining dictionary keys I would use parentheses to close the tuples, for example: P[(i,0)]=0 to avoid confusing anyone with any special handling of indexes.
answered by 06.11.2017 / 17:22
source