If you are not familiar with partitions, I advise you visit this page. It explains it nicely: https://en.m.wikipedia.org/wiki/Partition_(number_theory)
For some context, the problem I am trying to solve involves partitioning: I am trying to return the number of possible partitions of integers that add to a given sum that has no duplicate integers.
Here is a quick example: if you input 10, the partitions (9,1) and (8,2) would count because each value is unique, and the sum of the partitions is 10. However, if the partition is something like (5,2,1,1,1,) it will not pass since once it is broken down into just its unique values, it is (5,2,1,), which does not add to 10.
I coded a solution that gets the job done with lower numbers, like 10. However, the problem has a test case of 200, and it is taking a very long time to run.
I know that the problem is that partitioning is inherently exponential, but I don't think it is within my capabilities to come up with a way to optimize the code I have.
Here is my code:
def solution(n):
arr = []
count = 0
def partitions(num, I=1):
yield (num,)
for i in range(I, num//2 + 1):
for p in partitions(num-i, i):
yield (i,) + p
arr = list(partitions(n))
for part in arr:
if sum(sorted(list(set(part)))) == n and len(part) > 1:
count += 1
return count
#input: 10 ---> output: 9
#input: 3 ---> output: 1
#input: 50 ---> output: 3657