Skip to content

Instantly share code, notes, and snippets.

@lispandfound
Created August 23, 2017 01:45
Show Gist options
  • Save lispandfound/91d4ead9d73ef14cea6d2138c9dff1fb to your computer and use it in GitHub Desktop.
Save lispandfound/91d4ead9d73ef14cea6d2138c9dff1fb to your computer and use it in GitHub Desktop.
Knapsack
def value_of(knapsack, configuration):
values = zip(knapsack, configuration)
return sum(value for value, stolen in values
if stolen is True)
def combinations_of(length):
lst = [False] * length
for i in range(2 ** length):
for j in range(len(lst)):
bit_set = i & (1 << j)
if bit_set != 0:
lst[j] = True
else:
lst[j] = False
yield lst
def solve_knapsack(knapsack, limit):
optimal_solution = [False] * len(knapsack)
optimal_value = 0
for configuration in combinations_of(len(knapsack)):
config_value = value_of(knapsack, configuration)
valuable = config_value > optimal_value
valid = config_value <= limit
if valid and valuable:
optimal_solution = configuration[:]
optimal_value = config_value
return optimal_solution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment