We are given a 2D array and asked to write a fuction that will search the array for a specific subset of elements that sum up to the given target sum and return True, if it finds the subset and False otherwise. The specificity of this subset is the condition that any two of the elements must not be taken from the same column or row of the 2D array. For example, for an array:
T=[[1,2,3,4], [5,6,7,8], [9,5,6,7], [2,4,6,8]]
and target sum: target_sum = 26
the output should be True, because T[0][1]+T[1][2]+T[2][0]+T[3][3] == 2+7+9+8 == 26,
The same for the same array and target_sum = 20, because T[0][0]+T[1][3]+T[2][1]+T[3][2]==20
This is what I tried:
def given_sum(T, target_sum, row=-1, current_sum=0, columns=set()):
if target_sum==current_sum:
return True
if current_sum>target_sum:
return False
if row>=len(T)-1:
return False
row+=1
for col in range(len(T)):
if col in columns:
continue
columns.add(col)
return given_sum(T, target_sum, row, current_sum+T[row][col],columns)
columns.remove(col)
For the example array as above:
T=[[1,2,3,4], [5,6,7,8], [9,5,6,7], [2,4,6,8]]
and target_sum = 21, it prints True, because T[0][0]+T[1][1]+T[2][2]+T[3][3]==21,
but for target_sum = 26, it prints False despite the fact that T[0][1]+T[1][2]+T[2][0]+T[3][3]==26
Please help!