Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
bug in subset sum algorithm
#1
Given an array of integers and a value k, return True if there exists a subset of elements of the array that sums up to k.
This is my algorithm. Initially, the line that I commented was included and the result was that the algorithm outputted True when the answer should have been False. Without the line it seems to work fine. I do not understand why there is a difference in output, can somebody explain?

def solve(arr,items,sum,dp):
    if sum - arr[items] >= 0:
        dp[items][sum] = max(dp[items-1][sum],dp[items-1][sum-arr[items]])
    else:
        dp[items][sum] = dp[items-1][sum]

def driver(arr,k):
    dp = [[False for j in range(k+1)] for i in range(len(arr))]
    for i in range(len(arr)):
        dp[i][0] = True
        #why does this not work if the line below is executed?
        #dp[i][arr[i]] = True
    for i in range(len(arr)):
        for j in range(k+1):
            solve(arr,i,j,dp)
    return dp[len(arr)-1][k]
Reply


Messages In This Thread
bug in subset sum algorithm - by usercat123 - Feb-06-2022, 12:23 PM
RE: bug in subset sum algorithm - by deanhystad - Feb-06-2022, 03:41 PM
RE: bug in subset sum algorithm - by usercat123 - Feb-06-2022, 04:45 PM
RE: bug in subset sum algorithm - by deanhystad - Feb-07-2022, 05:41 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  how to refer to a subset of a list Skaperen 4 3,351 Jan-16-2022, 02:16 AM
Last Post: Skaperen
  How to create subset in python? Bhavika 5 3,159 Nov-27-2021, 07:16 PM
Last Post: Gribouillis
  Grabbing a Subset of a String acemurdoc 3 3,370 Jun-18-2019, 04:57 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020