implementing Implementing the Knapsack solution in Python - Dynamic Programming Solution Not Returning Expected Results
I'm wondering if anyone has experience with I'm optimizing some code but I'm working on a project and hit a roadblock... After trying multiple solutions online, I still can't figure this out. I'm trying to implement a dynamic programming solution for the 0/1 Knapsack question in Python, but I keep getting incorrect results for certain input values. Here's my code: ```python def knapsack(weights, values, capacity): n = len(values) K = [[0 for x in range(capacity + 1)] for x in range(n + 1)] for i in range(n + 1): for w in range(capacity + 1): if i == 0 or w == 0: K[i][w] = 0 elif weights[i-1] <= w: K[i][w] = max(values[i-1] + K[i-1][w - weights[i-1]], K[i-1][w]) else: K[i][w] = K[i-1][w] return K[n][capacity] ``` When I test it with the following inputs: ```python weights = [1, 2, 3] values = [10, 15, 40] capacity = 6 print(knapsack(weights, values, capacity)) # Expected output: 55 ``` I expect the output to be 55, but I am getting 40 instead. I have double-checked the weights and values arrays, and they seem to be correct. I also verified that the dynamic programming table is being filled out as expected, but the final result isn't what I anticipated. I suspect there might be an off-by-one behavior or a logic scenario within the nested loops. I've tried adding print statements to verify the values of `K[i][w]`, but I still need to figure it out. Can anyone spot what's going wrong? I've verified that I'm running Python 3.9.1 and using basic lists for the DP table. Any insights would be greatly appreciated! This is part of a larger web app I'm building. Is there a simpler solution I'm overlooking? My development environment is Windows 10. What's the correct way to implement this? This is my first time working with Python latest. Could this be a known issue?