To encapsulate the Rosetta Code knapsack 0-1 problem, we created a Python class called Knapsack01Problem. This class is contained in the knapsack.py file, which can be found at the following link:
https://github.com/PacktPublishing/Hands-On-Genetic-Algorithms-with-Python/blob/master/Chapter04/knapsack.py
The class provides the following methods:
- __init_data(): Initializes the RosettaCode.org knapsack 0-1 problem data by creating a list of tuples. Each tuple contains the name of an item, followed by its weight and its value.
- getValue(zeroOneList): Calculates the value of the chosen items in the list, while ignoring items that will cause the accumulating weight to exceed the maximum weight.
- printItems(zeroOneList) ...