interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / knapsack-problem-0-1 / oracle.py

29 lines · 1532 bytes Raw Blame History
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.
3from itertools import combinations
4items = [('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
6order = sorted(range(len(items)), key=lambda i: -items[i][2] / items[i][1])
7best = (0, ())
8def 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
15def 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)
25go(0, 0, 0, ())
26for i in sorted(best[1]):
27 print(items[i][0])
28print("total weight", sum(items[i][1] for i in best[1]))
29print("total value", best[0])