My goal is to write a function that takes a number and returns the number of solutions for that number, a form along the lines of f(a) = x_0 + x_1 +...+ x_n = a. where n can be any number such that n < a. Another restriction that I'm trying to implement is the return of only sets with unique elements as solutions. For example, f(4) would return the sets {4}, {1,3}. {2,2} would not be included because it has non-unique elements (I'm also ignoring {0,4} and {0,1,3}).
So far I've been able to solve all pairs that add up to any number, but for triplets and beyond I'd like to use a recursive function, which has been problematic. Here's what I have so far:
global results
results = []
global temp
temp = []
def solve(n):
for i in range(n,0,-1):
if n == i:
results.append([i])
else:
temp = [i]
loop(n, i,temp)
return results
def loop(n, i, total):
for j in range(min(total),0,-1):
if i + j < n:
temp.append(j)
loop(n,temp)
else:
if i + j == n:
results.append([i,j])
temp.pop()
else:
temp = []
print solve(4)
I'm not sure of my use of global variables or recursive functions but I do know it's not working. Pointers or suggestions would be most helpful.
Thanks