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 7784341
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T20:04:48+00:00 2026-06-01T20:04:48+00:00

Right now I am attempting to code the knapsack problem in Python 3.2. I

  • 0

Right now I am attempting to code the knapsack problem in Python 3.2. I am trying to do this dynamically with a matrix. The algorithm that I am trying to use is as follows

Implements the memoryfunction method for the knapsack problem 
Input: A nonnegative integer i indicating the number of the first
items being considered and a nonnegative integer j indicating the knapsack's capacity
Output: The value of an optimal feasible subset of the first i items
Note: Uses as global variables input arrays Weights[1..n], Values[1...n]
and table V[0...n, 0...W] whose entries are initialized with -1's except for
row 0 and column 0 initialized with 0's
if V[i, j] < 0
    if j < Weights[i]
        value <-- MFKnapsack(i - 1, j)

    else
        value <-- max(MFKnapsack(i -1, j),
            Values[i] + MFKnapsack(i -1, j - Weights[i]))

    V[i, j} <-- value

return V[i, j]

If you run the code below that I have you can see that it tries to insert the weight into the the list. Since this is using the recursion I am having a hard time spotting the problem. Also I get the error: can not add an integer with a list using the ‘+’. I have the matrix initialized to start with all 0’s for the first row and first column everything else is initialized to -1. Any help will be much appreciated.

#Knapsack Problem 


def knapsack(weight,value,capacity):
    weight.insert(0,0)
    value.insert(0,0)

    print("Weights: ",weight)
    print("Values: ",value)

    capacityJ = capacity+1

    ## ------ initialize matrix F ---- ##
    dimension = len(weight)+1
    F = [[-1]*capacityJ]*dimension

    #first column zeroed
    for i in range(dimension):
        F[i][0] = 0
    #first row zeroed            
    F[0] = [0]*capacityJ
    #-------------------------------- ##

    d_index = dimension-2
    print(matrixFormat(F))

    return recKnap(F,weight,value,d_index,capacity)

def recKnap(matrix, weight,value,index, capacity):

    print("index:",index,"capacity:",capacity)
    if matrix[index][capacity] < 0:
        if capacity < weight[index]:
            value = recKnap(matrix,weight,value,index-1,capacity)
        else:
            value = max(recKnap(matrix,weight,value,index-1,capacity),
                        value[index] +
                        recKnap(matrix,weight,value,index-1,capacity-(weight[index]))

    matrix[index][capacity] = value
    print("matrix:",matrix)


    return matrix[index][capacity]


def matrixFormat(*doubleLst):
    matrix = str(list(doubleLst)[0])
    length = len(matrix)-1
    temp = '|'
    currChar = ''
    nextChar = ''
    i = 0

    while i < length:
        if matrix[i] == ']':
            temp = temp + '|\n|'
        #double digit
        elif matrix[i].isdigit() and matrix[i+1].isdigit():
            temp = temp + (matrix[i]+matrix[i+1]).center(4)
            i = i+2
            continue
        #negative double digit
        elif matrix[i] == '-' and matrix[i+1].isdigit() and matrix[i+2].isdigit():
            temp = temp + (matrix[i]+matrix[i+1]+matrix[i+2]).center(4)
            i = i + 2
            continue
        #negative single digit
        elif matrix[i] == '-' and matrix[i+1].isdigit():
            temp = temp + (matrix[i]+matrix[i+1]).center(4)
            i = i + 2
            continue




        elif matrix[i].isdigit():
            temp = temp + matrix[i].center(4)

        #updates next round
        currChar = matrix[i]
        nextChar = matrix[i+1]
        i = i + 1

    return temp[:-1]




def main():
    print("Knapsack Program")
    #num = input("Enter the weights you have for objects you would like to have:")
    #weightlst = []
    #valuelst = []
##    for i in range(int(num)):
##        value , weight = eval(input("What is the " + str(i) + " object value, weight you wish to put in the knapsack?  ex. 2,3: "))
##        weightlst.append(weight)
##        valuelst.append(value)
    weightLst = [2,1,3,2]
    valueLst = [12,10,20,15]
    capacity = 5

    value = knapsack(weightLst,valueLst,5)

    print("\n      Max Matrix")
    print(matrixFormat(value))

main()
  • 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-06-01T20:04:49+00:00Added an answer on June 1, 2026 at 8:04 pm
    F = [[-1]*capacityJ]*dimension
    

    does not properly initialize the matrix. [-1]*capacityJ is fine, but [...]*dimension creates dimension references to the exact same list. So modifying one list modifies them all.

    Try instead

    F = [[-1]*capacityJ for _ in range(dimension)]
    

    This is a common Python pitfall. See this post for more explanation.

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

Sidebar

Related Questions

Right now I can use this URL to request a Google Static Maps image
I'm developing a facebook app right now all by my lonesome. I'm attempting to
Right now I have this SQL query which is valid but always times out:
Right now I have double numba = 5212.6312 String.Format({0:C}, Convert.ToInt32(numba) ) This will give
Right now I've hard coded the whole xml file in my python script and
Consider this code attempting to create an Active Directory account. It's generating an exception
I'm trying to customize the UIImagePickerController for iPhone right now. I could modify the
Ok, I am attempting to use this custom extension to perform an entity update.
I'm attempting to have a UITableView that I can dynamically add and remove rows
I am attempting to develop a game with canvas element. Right now, I am

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.