So I'm encountering a weird problem.
def findFourPlus(itemCount, seq, goal):
goalDifference = float("inf")
closestPartial = []
hello = subset_sum(itemCount, seq, goal, goalDifference, closestPartial, partial=[])
return hello #doesn't return value from subset_sum()
def subset_sum(itemCount, seq, goal, goalDifference, closestPartial, partial):
s = sum(partial)
# check if the partial sum is equals to target
if(len(partial) == itemCount):
if s == goal:
print("FOUND YAA")
return partial #right now doesn't return anything. I intend for it to break out of this function as soon as it finds one pair of solution.
else:
if( abs(goal - s) < goalDifference):
#print(abs(goal-s), goalDifference, closestPartial)
goalDifference = abs(goal - s)
closestPartial[:] = partial
#print(abs(goal-s), goalDifference, closestPartial)
return closestPartial
for i in range(len(seq)):
n = seq[i]
remaining = seq[i+1:]
print(subset_sum(itemCount, remaining, goal, goalDifference, closestPartial, partial + [n]))
In the subset_sum() function, I can print out the partial variable, and it will return to me the right value
>>> findFourPlus(3, [1,2,3,4,5,6,7,8,9,10], 20)
FOUND YAA
[1, 9, 10]
FOUND YAA
[2, 8, 10]
FOUND YAA
[3, 7, 10]
FOUND YAA
[3, 8, 9]
FOUND YAA
[4, 6, 10]
FOUND YAA
[4, 7, 9]
FOUND YAA
[5, 6, 9]
FOUND YAA
[5, 7, 8]
However, if i change the print(partial) line to return partial, it will still print out the FOUNDYAA line since it is printed, but it will not return the partial
>>> findFourPlus(3, [1,2,3,4,5,6,7,8,9,10], 20)
FOUND YAA
FOUND YAA
FOUND YAA
FOUND YAA
FOUND YAA
FOUND YAA
FOUND YAA
FOUND YAA
I wrote other functions before I wrote findFourPlus and subset_sum, and those worked fine when I attempt to return something. What am i doing wrong here?
Edit: I seem to be confusing the readers here. What I am ultimately trying to do is to store the sets of integeres (the list ) in a variable by calling the findFourPlus() function. Say I want to see if, in the list [1,2,3,4,5], would any two of them add up equal 5, I would call findFourPlus(2, [1,2,3,4,5], 5), and it would hopefully return to me [1, 4]. With that, I can store the answer [1,4] into a variable, say answer, by calling
answer = findFourPlus(2, [1,2,3,4,5], 5) // if I call answer, it'll return to me [1,4]
An example:
>>> a = findFourPlus(2, [1,2,3,4,5], 6) # prints out everything, which is good for test cases
[1, 2]
[1, 3]
[1, 4]
FOUND YAA
[1, 5]
None
[2, 3]
FOUND YAA
[2, 4]
[2, 5]
None
[3, 4]
[3, 5]
None
[4, 5]
None
None
>>> a # doesn't return anything when called
>>>
The printing are all just to make sure my logic is correct. Sorry for the confusion, but hopefully this clarifies it!