Created
August 10, 2014 22:21
-
-
Save okoye/168f5ae70e57043fb9b3 to your computer and use it in GitHub Desktop.
python solution to the subset-sum problem. A bruteforce approach
This file contains 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 subsetsum(numbers, target): | |
size = 1 | |
subsets = [] | |
while size <= len(numbers): | |
for combination in combinations(numbers, size): | |
if sum(combination) == target: | |
subsets.append(combination) | |
size += 1 | |
return subsets | |
def combinations(numbers, size): | |
if len(numbers) <= 0 or size <= 0: | |
yield [] | |
else: | |
for index, number in enumerate(numbers): | |
for combination in combinations(numbers[index+1:], size-1): | |
yield [number]+combination |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment