Skip to content

Instantly share code, notes, and snippets.

@KHN190
Created January 18, 2019 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KHN190/4f04b42c9157c3ecf16ee30b5a12540e to your computer and use it in GitHub Desktop.
Save KHN190/4f04b42c9157c3ecf16ee30b5a12540e to your computer and use it in GitHub Desktop.
Solution for complete knapsack problem.
costs = [3,5,9]
value = [5,9,16]
volume = 1303
# solutions
opts = set()
opts.add(tuple([0]))
# calc total value
cost_val = dict(zip(costs, value))
def total_value(opt):
return sum([cost_val.get(cost, 0) for cost in opt])
def possible_solutions():
solutions = set()
for opt in opts:
for cost in costs:
if cost + sum(opt) > volume:
continue
cnt = (volume - sum(opt)) // cost
for _ in range(cnt + 1):
sol = tuple(list(opt) + [cost] * _)
solutions.add(sol)
return solutions
def optimize_max_return(opts):
cur = list(opts)[0]
for sol in opts:
if total_value(sol) > total_value(cur):
cur = sol
return cur
while sum(optimize_max_return(opts)) <= volume - min(costs):
opts = opts.union(possible_solutions())
print(optimize_max_return(opts), total_value(optimize_max_return(opts)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment