I'm almost a beginner programmer that wants to learn how to write algorithms.I just wrote a program that finds the shortest subarray(subset) in an array, whose sum of indexes in the given array equals the sum of the elements of the subarray(subset) and prints out the sum. The problem is, I needed to keep track of both the amount of numbers in the subarray(to find the shortest one) as well as the sum of the chosen elements(because I want to save it or just print it), so I would like to return a 2-element array recursively, but any way I try it, I end up having an error like "NoneType is not subscriptable" or '<' not supported between instances of 'NoneType' and 'NoneType'. So I used a global variable and solved it that way. But how do I avoid using a global variable in this type of problem? Here is my code, please teach me how to solve this type of problem without a global variable:
best_sum = math.inf
def SumIndexesEqualSumElements(T, idx=0, idxsum=0, tabsum=0, count=0):
global best_sum
if idx==len(T):
if count==0:
return math.inf
if idxsum==tabsum:
best_sum = tabsum
return count
return math.inf
return min(SumIndexesEqualSumElements(T,idx+1,idxsum+idx,tabsum+T[idx],count+1),
SumIndexesEqualSumElements(T,idx+1,idxsum,tabsum,count))
SumIndexesEqualSumElements([1,7,3,5,11,2])
print(best_sum)