So I made a recursive function that gives me all the subarrays , I want to apply a condition on those sub-arrays and then keep a count of subarrays that satisfy the condition. But Initialization of count variable has been bothering me ,please help!
here is my code:
def printSubArrays(arr, start, end):
if end == len(arr):
return
elif start > end:
return printSubArrays(arr,0,end+1)
else:
dictio = arr[start:end + 1]
print(dictio)
if len(dictio)!=1:
for i in range(len(dictio)):
aand =1
aand =aand & dictio[i]
if aand %2 !=0:
count=count+1
return printSubArrays(arr,start+1,end)
arr=[1,2,5,11,15]
dictio=[]
count = 0
printSubArrays(arr,0,0)
print(count)
The most common technique to keep a count is to use a helper function. So you'd have your principal function call a helper like this:
def printSubArrays(arr, start, end):
return _printSubArrays(arr, start, end, 0)
The 0 at the end is the count.
Then each time you recurse you increment:
def _printSubArrays(arr, start, end, count):
if end == len(arr):
return count
elif start > end:
return _printSubArrays(arr,0,end+1, count + 1)
else:
dictio = arr[start:end + 1]
print(dictio)
if len(dictio)!=1:
for i in range(len(dictio)):
aand =1
aand =aand & dictio[i]
if aand %2 !=0:
count=count+1
return _printSubArrays(arr,start+1,end, count+1)