pythonpython-3.xknapsack-problem

my knapsack code does not work in python 3 can anyone help what is the problem with my code?


def knapSack(W, wi, pi, i):
    
    if i == 0 or W == 0:
        return 0

    if (wi[i-1] > W):
        return knapSack(W, wi, pi, i-1)

    else:
        return max(
            pi[n-1] + knapSack(
                W-wi[n-1], wi, pi, n-1),
            knapSack(W, wi, pi, n-1))

pi = [25, 5, 20, 120, 100, 0, 30, 0, 0, 75, 100]
wi = [2, 4, 1, 8, 10, 5, 3, 7, 6, 12, 7]
W = 30
n = len(pi)
knapSack(W, wi, pi, n)

I expect the answer of function at the end but I keep getting errors . I get (maximum recursion depth exceeded)error but I don't think it's the problem .


Solution

  • The knappSack() function is given the parameter i but in the function you are still using n, which will stay the same in the recursions. Changing to

    def knapSack(W, wi, pi, i):
        
        if i == 0 or W == 0:
            return 0
    
        if (wi[i-1] > W):
            return knapSack(W, wi, pi, i-1)
    
        else:
            return max(
                pi[i-1] + knapSack(W-wi[i-1], wi, pi, i-1),
                knapSack(W, wi, pi, i-1))
    
    pi = [25, 5, 20, 120, 100, 0, 30, 0, 0, 75, 100]
    wi = [2, 4, 1, 8, 10, 5, 3, 7, 6, 12, 7]
    W = 30
    n = len(pi)
    knapSack(W, wi, pi, n)
    

    should solve the issue.