'Print subsequence which have sum 0 in Python list
I have a Numpy array (arr) and want to print all subsequences such that sum of values in the subsequence equals to zero. I have a code but in this I get subArrays.
def findSubArrays(arr,n):
hashMap = {}
out = []
sum1 = 0
for i in range(n):
sum1 += arr[i]
if sum1 == 0:
out.append((0, i))
al = []
if sum1 in hashMap:
al = hashMap.get(sum1)
for it in range(len(al)):
out.append((al[it] + 1, i))
al.append(i)
hashMap[sum1] = al
return out
def printOutput(output):
for i in output:
print ("Subarray found from Index " +
str(i[0]) + " to " + str(i[1]))
if __name__ == '__main__':
arr = [6, 3, -1, -3, 4, -2,
2, 4, 6, -12, -7]
n = len(arr)
out = findSubArrays(arr, n)
if (len(out) == 0):
print ("No subarray exists")
else:
printOutput (out)
This code returns the subArrays which will have sum equals zero. But I want subsequences with size of the output subsequence greater than 2 and less than 7. I want to get the index of values in those subsequences.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
