Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading