I have a function that works exactly how I want it to, but for my course work, I have to turn this function into a class that:
- Must have a function called
solveIt, - returns the following two values:
- a boolean that is True if you've solved this knapsack problem, and
- the knapsack object with the correct values in it.
The class must have a __str__() function that returns a string like this. The first line is the size, and the second is a comma-separated list of the elements:
10 4,1,9,2,0,4,4,4,3,7 I dont understand classes that well, so any help will be appreciated. Here is the function I have right now:
from itertools import combinations def com_subset_sum(seq, target): if target == 0 or target in seq: print(target) return True for r in range(len(seq),1,-1): for subset in combinations(seq, r): if sum(subset) == target: print(subset) return True return False print(com_subset_sum([4,1,9,2,0,4,4,4,3,7],10))
Knapsackclass. Or, if you wanted to be able to evaluate the same sequence with a variety of different targets, and maybe keep track of all the targets you've checked for. Or… there are lots of good reasons. Of course, there's one all-too-common bad reason: an instructor who has no idea how to write a good assignment. But I don't want to just assume that…