I am working with partitions (number theory). I want to write a function that will tell me the average length of the partitions of a number. For example. The partitions of the number 4 are:
1+1+1+1
1+1+2
1+3
2+2
4
I borrowed this function from another question on here, which prints you all of the ways to add a list of numbers to a given number:
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([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15],15)
Outputs:
sum([3, 8, 4])=15
sum([3, 5, 7])=15
sum([8, 7])=15
sum([5, 10])=15
And I modified it to allow for repeats by changing:
remaining = numbers[i+1:]
to:
remaining = numbers[i:]
Then I added two parameters to the function:
def subset_sum(numbers, target, length_twos=[0], partitions_with_twos=[0],
partial=[]):
and I added inside the function to say:
if s == target:
if 2 in partial:
length_twos[0]+=len(partial)
partitions_with_twos[0]+=1
Then at the end I wanted to find out the average length of partitions that contained a 2 was. But it's not giving me the right answer. Any idea why? For example, the average for the number 4 should be 2.5.
Of course I also modified the subset_sum()
within the function to include the parameters recursively. Like so.
for i in range(len(numbers)):
n = numbers[i]
remaining = numbers[i+1:]
subset_sum(remaining, target, length_twos, partitions_with_twos,
partial + [n])