Skip to content

Instantly share code, notes, and snippets.

@dniku
Created March 19, 2015 17:54
Show Gist options
  • Select an option

  • Save dniku/d9bc214daefeb90f66eb to your computer and use it in GitHub Desktop.

Select an option

Save dniku/d9bc214daefeb90f66eb to your computer and use it in GitHub Desktop.
Expansions of a natural number into sums
def get_expansions(num, nterms):
result = []
def run(cur_sum, cur_vals, remain):
if remain == 0:
if cur_sum == num:
result.append(tuple(cur_vals))
return
elif remain == 1:
cur_vals.append(num - cur_sum)
run(num, cur_vals, 0)
cur_vals.pop()
else:
for term in xrange(1, num - cur_sum):
cur_vals.append(term)
run(cur_sum + term, cur_vals, remain - 1)
cur_vals.pop()
run(0, [], nterms)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment