Created
April 28, 2011 20:46
-
-
Save mlbright/947302 to your computer and use it in GitHub Desktop.
Subset sum problem
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
| # From hacker news | |
| # http://apps.ycombinator.com/item?id=2267312 | |
| def subset_summing_to_zero(activities): | |
| subsets = {0: []} | |
| for (activity, cost) in activities.iteritems(): | |
| old_subsets = subsets | |
| subsets = {} | |
| for (prev_sum, subset) in old_subsets.iteritems(): | |
| subsets[prev_sum] = subset | |
| new_sum = prev_sum + cost | |
| new_subset = subset + [activity] | |
| if 0 == new_sum: | |
| new_subset.sort() | |
| return new_subset | |
| else: | |
| subsets[new_sum] = new_subset | |
| return [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment