I am trying to print the sum of all the subsets of an array using recursion.. But I am only getting one sum and the scope of the variable inside my recursive function is losing, because of that next recursion logic is failing or my complete recursive logic is not proper...
Note: May be I am not able to explain my approach well in the description.. but you can understand what I am trying to do by looking at the code..
The variable localTempArray is losing the scope after first cycle of recursion..and I am using it to make another recursive call
Please help me to understand recursion well...
Thanks
import sys
a = [2,4,8,16,32,64,128,256,512,1024]
print len(a)
def arrayPop(temp,i):
try:
temp.pop(i)
return temp
except:
return temp
def recursiveSum(tempArray):
localTempArray = tempArray
print localTempArray
if (len(tempArray) == 0):
return 0
ybinarysum = localTempArray[0] + recursiveSum(arrayPop(tempArray,0))
print localTempArray
recursiveSum(arrayPop(localTempArray,0))
return ybinarysum
recursiveSum(a)
Current Output:
10
[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
[4, 8, 16, 32, 64, 128, 256, 512, 1024]
[8, 16, 32, 64, 128, 256, 512, 1024]
[16, 32, 64, 128, 256, 512, 1024]
[32, 64, 128, 256, 512, 1024]
[64, 128, 256, 512, 1024]
[128, 256, 512, 1024]
[256, 512, 1024]
[512, 1024]
[1024]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
[]
localTempArray = tempArraydoes NOT make a separate copy of the array. Both names refer to the same object.