Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4324466
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T09:08:09+00:00 2026-05-21T09:08:09+00:00

So I have to solve the knapsack problem for class. So far, I’ve come

  • 0

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).

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.

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 >= 0
    comparator: function taking two tuples and returning a bool
    returns: dictionary mapping subject name to (value, work)
    """

    optimal = {}
    while maxWork > 0:
        new_subjects = dict((k,v) for k,v in subjects.items() if v[1] < 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  

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!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T09:08:10+00:00Added an answer on May 21, 2026 at 9:08 am

    Using a simple greedy algorithm will not provide any bounds on the quality of the solution in comparison to OPT.

    Here is a fully polynomial time (1 – epsilon) * OPT approximation psuedocode for knapsack:

    items = [...]  # items
    profit = {...} # this needs to be the profit for each item
    sizes = {...}  # this needs to be the sizes of each item
    epsilon = 0.1  # you can adjust this to be arbitrarily small
    P = max(items) # maximum profit of the list of items
    K = (epsilon * P) / float(len(items))
    for item in items:
        profit[item] = math.floor(profit[item] / K)
    return _most_prof_set(items, sizes, profit, P)
    

    We need to define the most profitable set algorithm now. We can do this with some dynamic programming. But first lets go over some definitions.

    If P is the most profitable item in the set, and n is the amount of items we have, then nP is clearly a trivial upper bound on the profit allowed. For each i in {1,…,n} and p in {1,…,nP} we let Sip denote a subset of items whose total profit is exactly p and whose total size is minimized. We then let A(i,p) denote the size of set Sip (infinity if it doesn’t exist). We can easily show that A(1,p) is known for all values of p in {1,…,nP}. We will define a recurrance to compute A(i,p) which we will use as a dynamic programming problem, to return the approximate solution.

    A(i + 1, p) = min {A(i,p), size(item at i + 1 position) + A(i, p - profit(item at i + 1 position))} if profit(item at i + 1) < p otherwise A(i,p)
    

    Finally we give _most_prof_set

    def _most_prof_set(items, sizes, profit, P):
        A = {...}
        for i in range(len(items) - 1):
            item = items[i+1]
            oitem = items[i]
            for p in [P * k for k in range(1,i+1)]:
                if profit[item] < p:
                    A[(item,p)] = min([A[(oitem,p)], \
                                         sizes[item] + A[(item, p - profit[item])]])
                else:
                    A[(item,p)] = A[(oitem,p)] if (oitem,p) in A else sys.maxint
        return max(A) 
    

    Source

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have to solve a little mpi problem. I have 4 slaves processes and
I have to write a C app that will act as both UDP sender
As part of my lecture in C++ the students will have to solve assignments.
I am writing C# code that call a C library and something it is
I'm fairly new to C and have started out writing a small library with
I'm trying to write a java code on an Android emulator that will send
I needed some help with plotting a velocity vs forcing term diagram for a
I want to select some data from the sqllite Db. Now I face a
I am developing an applet for browser-to-browser application where User A knows User B's

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.