Note that there are some explanatory texts on larger screens.

plurals
  1. POknapsack problem (classic)
    primarykey
    data
    text
    <p>So I have to solve the knapsack problem for class. So far, I've come up with the following. My comparators are functions that determine which of two subjects will be the better option (by looking at the corresponding (value,work) tuples).</p> <p>I decided to iterate over the possible subjects with work less than maxWork, and in order to find which subject is the best option at any given turn, I compared my most recent subject to all the other subjects that we have not used yet.</p> <pre><code>def greedyAdvisor(subjects, maxWork, comparator): """ Returns a dictionary mapping subject name to (value, work) which includes subjects selected by the algorithm, such that the total work of subjects in the dictionary is not greater than maxWork. The subjects are chosen using a greedy algorithm. The subjects dictionary should not be mutated. subjects: dictionary mapping subject name to (value, work) maxWork: int &gt;= 0 comparator: function taking two tuples and returning a bool returns: dictionary mapping subject name to (value, work) """ optimal = {} while maxWork &gt; 0: new_subjects = dict((k,v) for k,v in subjects.items() if v[1] &lt; maxWork) key_list = new_subjects.keys() for name in new_subjects: #create a truncated dictionary new_subjects = dict((name, new_subjects.get(name)) for name in key_list) key_list.remove(name) #compare over the entire dictionary if reduce(comparator,new_subjects.values())==True: #insert this name into the optimal dictionary optimal[name] = new_subjects[name] #update maxWork maxWork = maxWork - subjects[name][1] #and restart the while loop with maxWork updated break return optimal </code></pre> <p>The problem is I don't know why this is wrong. I'm getting errors and I have no idea where my code is wrong (even after throwing in print statements). Help would be much appreciated, thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload