| 1 | """Help our clients spend as much of their vouchers as possible. |
|---|
| 2 | |
|---|
| 3 | One-over-N click shopping. |
|---|
| 4 | """ |
|---|
| 5 | |
|---|
| 6 | |
|---|
| 7 | def raw_knap(i, W, w, v): |
|---|
| 8 | """Calculate m[i, W]. |
|---|
| 9 | |
|---|
| 10 | Parameters |
|---|
| 11 | ---------- |
|---|
| 12 | i : int |
|---|
| 13 | Consider only first i items of w. |
|---|
| 14 | W : float |
|---|
| 15 | Maximum weight the sack can hold. |
|---|
| 16 | w : list of floats |
|---|
| 17 | Weights of items we're trying to put in the sack. |
|---|
| 18 | v : list of floats |
|---|
| 19 | Values of items we're trying to put in the sack. |
|---|
| 20 | |
|---|
| 21 | Return |
|---|
| 22 | ------ |
|---|
| 23 | max_value : float |
|---|
| 24 | Maximum value. |
|---|
| 25 | max_weight : float |
|---|
| 26 | Weight of items that make up maximum value. |
|---|
| 27 | items : list of int |
|---|
| 28 | List of items from w that make up maxw. |
|---|
| 29 | """ |
|---|
| 30 | if i == 0: |
|---|
| 31 | return 0, 0, [] |
|---|
| 32 | elif W <= 0: |
|---|
| 33 | return 0, 0, [] |
|---|
| 34 | else: |
|---|
| 35 | max_v, max_w, items = raw_knap(i-1, W, w, v) |
|---|
| 36 | vi, wi = v[i-1], w[i-1] |
|---|
| 37 | if wi <= W: |
|---|
| 38 | max_vi, max_wi, items_i = raw_knap(i-1, W-wi, w, v) |
|---|
| 39 | if max_vi + vi > max_v: |
|---|
| 40 | max_v, max_w, items = max_vi + vi, max_wi + wi, items_i + [i-1] |
|---|
| 41 | return max_v, max_w, items |
|---|
| 42 | |
|---|
| 43 | |
|---|
| 44 | def knap(w, W): |
|---|
| 45 | """Calculate maximum weight of items for w than can fit into W. |
|---|
| 46 | |
|---|
| 47 | Parameters |
|---|
| 48 | ---------- |
|---|
| 49 | w : list of floats |
|---|
| 50 | Items we're trying to put in the sack. |
|---|
| 51 | W : float |
|---|
| 52 | Maximum weight the float can hold. |
|---|
| 53 | |
|---|
| 54 | Return |
|---|
| 55 | ------ |
|---|
| 56 | max_weight : float |
|---|
| 57 | Maximum weight. |
|---|
| 58 | items : list of float |
|---|
| 59 | List of items from w that make up maxw. |
|---|
| 60 | """ |
|---|
| 61 | result = raw_knap(len(w), W, w, w) |
|---|
| 62 | return result[0], result[2] |
|---|