Created
March 19, 2015 17:54
-
-
Save dniku/d9bc214daefeb90f66eb to your computer and use it in GitHub Desktop.
Expansions of a natural number into sums
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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