+ 2
Write a recursive function that prints the sum of all possible subsets of a given set S.
we have to give the input number of elements in set and in next line elements space seperated like:input1-3,input2-1 2 3;output-0 ,1 ,2 ,3 ,3 ,4 ,5 ,6.
3 odpowiedzi
+ 3
Here is the algorithm in Python:
def subset_sum(numbers, target, partial=[]): s = sum(partial)
# check if the partial sum is equals to target
if s == target: print "sum(%s)=%s" % (partial, target)
if s >= target: return # if we reach the number why bother to continue for i in range(len(numbers)): n = numbers[i] remaining = numbers[i+1:]
subset_sum(remaining, target, partial + [n]) if __name__ == "__main__": subset_sum([3,9,8,4,5,7,10],15)
#Outputs:
#sum([3, 8, 4])=15
#sum([3, 5, 7])=15
#sum([8, 7])=15
#sum([5, 10])=15
+ 2
why this code not answering correct-
please help
def subsetSum(arr, n):
total=2**n
for i in range(total):
sum=0
for j in range(n):
if((i and 2**j)!=0):
sum+=arr[j]
print(sum)
arr=[1,2,3]
n=len(arr)
subsetSum(arr, n)
+ 1
why recursive? using itertools.permutations you should get this without recursion