Knapsack Problem/Python: Difference between revisions

m
Fixed syntax highlighting.
(moved from Knapsack Problem)
 
m (Fixed syntax highlighting.)
 
(3 intermediate revisions by one other user not shown)
Line 1:
{{collection|Knapsack Problem}}
 
===Simple Brute-Force Solution===
 
<langsyntaxhighlight lang="python">class Bounty:
def __init__(self, value, weight, volume):
self.value, self.weight, self.volume = value, weight, volume
Line 35:
print "This is achieved by carrying (one solution) %d panacea, %d ichor and %d gold" % \
(best_amounts[0], best_amounts[1], best_amounts[2])
print "The weight to carry is %4.1f and the volume used is %5.3f" % (best.weight, best.volume)</langsyntaxhighlight>
 
===General Brute-Force Solution===
Requires Python V.2.6+
 
<lang python>from itertools import product, izip
This handles a varying number of items
<langsyntaxhighlight lang="python">from itertools import product, izip
from collections import namedtuple
 
Line 84 ⟶ 86:
item_names = ", ".join(item.name for item in items)
print " The number of %s items to achieve this is: %s, respectively." % (item_names, max_items)
print " The weight to carry is %.3g, and the volume used is %.3g." % (max_weight, max_volume)</langsyntaxhighlight>
 
Sample output
Line 91 ⟶ 93:
The weight to carry is 24.7, and the volume used is 0.247</pre>
 
===GeneralSpecific Dynamic Programming solution===
 
A dynamic programming approach using a 2-dimensional table (One dimension for weight and one for volume). Because this approach requires that all weights and volumes be integer, I multiplied the weights and volumes by enough to make them integer. This algorithm takes O(w*v) space and O(w*v*n) time, where w = weight of sack, v = volume of sack, n = number of types of items. To solve this specific problem it's much slower than the brute force solution.
 
<langsyntaxhighlight lang="python">from itertools import product, izip
from collections import namedtuple
 
Line 179 ⟶ 181:
item_names = ", ".join(item.name for item in items)
print " The number of %s items to achieve this is: %s, respectively." % (item_names, max_items)
print " The weight to carry is %.3g, and the volume used is %.3g." % (max_weight, max_volume)</langsyntaxhighlight>
 
Sample output
Line 185 ⟶ 187:
The number of panacea,ichor,gold items to achieve this is: [9, 0, 11], respectively
The weight to carry is 247, and the volume used is 247</pre>
 
===More General Dynamic Programming solution===
See [[Knapsack problem/Unbounded/Python dynamic programming‎]]
9,476

edits