omega-rosetta
aien-dev/omega-rosetta
Brought by drakestapleton
omega-rosetta / tasks / knapsack-problem-0-1 / oracle.py
| 1 | # Independent reference for "Knapsack problem/0-1" (Python 3, standard library only). |
| 2 | # expected.txt is this program's stdout; omc never produced it. |
| 3 | from itertools import combinations |
| 4 | items = [('map', 9, 150), ('compass', 13, 35), ('water', 153, 200), ('sandwich', 50, 160), ('glucose', 15, 60), ('tin', 68, 45), ('banana', 27, 60), ('apple', 39, 40), ('cheese', 23, 30), ('beer', 52, 10), ('suntan cream', 11, 70), ('camera', 32, 30), ('T-shirt', 24, 15), ('trousers', 48, 10), ('umbrella', 73, 40), ('waterproof trousers', 42, 70), ('waterproof overclothes', 43, 75), ('note-case', 22, 80), ('sunglasses', 7, 20), ('towel', 18, 12), ('socks', 4, 50), ('book', 30, 10)] |
| 5 | # exhaustive search is 2^22 subsets; branch and bound over items sorted by value density keeps it quick |
| 6 | order = sorted(range(len(items)), key=lambda i: -items[i][2] / items[i][1]) |
| 7 | best = (0, ()) |
| 8 | def bound(k, w, v): |
| 9 | for i in order[k:]: |
| 10 | if w + items[i][1] <= 400: |
| 11 | w += items[i][1]; v += items[i][2] |
| 12 | else: |
| 13 | return v + (400 - w) * items[i][2] / items[i][1] |
| 14 | return v |
| 15 | def go(k, w, v, chosen): |
| 16 | global best |
| 17 | if v > best[0]: |
| 18 | best = (v, chosen) |
| 19 | if k == len(order) or bound(k, w, v) <= best[0]: |
| 20 | return |
| 21 | i = order[k] |
| 22 | if w + items[i][1] <= 400: |
| 23 | go(k + 1, w + items[i][1], v + items[i][2], chosen + (i,)) |
| 24 | go(k + 1, w, v, chosen) |
| 25 | go(0, 0, 0, ()) |
| 26 | for i in sorted(best[1]): |
| 27 | print(items[i][0]) |
| 28 | print("total weight", sum(items[i][1] for i in best[1])) |
| 29 | print("total value", best[0]) |