Skip to content

Create Enhancement of the knapsack algorithm #9266 #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions Enhancement of the knapsack algorithm #9266
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
The following is a Python implementation of the 0-1 knapsack problem with memorization:

def knapsack_memorization(weights, values, capacity):
"""Solves the 0-1 knapsack problem using memorization.

Args:
weights: A list of weights of the items.
values: A list of values of the items.
capacity: The capacity of the knapsack.

Returns:
The maximum value of the items that can be placed in the knapsack.
"""

memo = {}

def knapsack_helper(i, capacity):
if i == 0 or capacity == 0:
return 0

key = (i, capacity)
if key in memo:
return memo[key]

if weights[i - 1] > capacity:
max_value = knapsack_helper(i - 1, capacity)
else:
max_value = max(knapsack_helper(i - 1, capacity),
values[i - 1] + knapsack_helper(i - 1, capacity - weights[i - 1]))

memo[key] = max_value
return max_value

return knapsack_helper(len(weights), capacity)



The following is a Python implementation of the 0-N knapsack problem:

def knapsack_0_n(weights, values, capacity):
"""Solves the 0-N knapsack problem.

Args:
weights: A list of weights of the items.
values: A list of values of the items.
capacity: The capacity of the knapsack.

Returns:
The maximum value of the items that can be placed in the knapsack.
"""

memo = {}

def knapsack_helper(i, capacity):
if i == 0 or capacity == 0:
return 0

key = (i, capacity)
if key in memo:
return memo[key]

max_value = 0
for j in range(1, capacity // weights[i - 1] + 1):
max_value = max(max_value, values[i - 1] * j + knapsack_helper(i - 1, capacity - weights[i - 1] * j))

memo[key] = max_value
return max_value

return knapsack_helper(len(weights), capacity)