Write a function that, given an input array of integers and a desired target_sum, returns the number of combinations, of any length, that add up to that target_sum.
Created
September 30, 2016 00:26
Star
You must be signed in to star a gist
Simple Python Code Challenge
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
from itertools import combinations | |
def count_sets(numbers, target): | |
count = 0 | |
for i in range(len(numbers)): | |
for j in combinations(numbers, i+1): | |
count += 1 if sum(j) == target else 0 | |
return count |
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
import unittest | |
from solution import count_sets | |
class SolutionTest(unittest.TestCase): | |
def test_empty(self): | |
arr = [] | |
target = 0 | |
expected_output = 0 | |
self.assertEqual(count_sets(arr, target), expected_output) | |
def test_negative_values(self): | |
arr = [1, 5, 2, -1, 4, -5] | |
target = 3 | |
expected_output = 4 | |
self.assertEqual(count_sets(arr, target), expected_output) | |
def test_no_sum(self): | |
arr = [7, 3, 5, 1, 3, 5, 7] | |
target = 2 | |
expected_output = 0 | |
self.assertEqual(count_sets(arr, target), expected_output) | |
def test_target_negative_exists(self): | |
arr = [4, 1, 2, -2, 2, -8] | |
target = -3 | |
expected_output = 4 | |
self.assertEqual(count_sets(arr, target), expected_output) | |
def test_target_negative_not_exists(self): | |
arr = [4, 6, 2, -2, 2, -8] | |
target = -5 | |
expected_output = 0 | |
self.assertEqual(count_sets(arr, target), expected_output) | |
def test_case_1(self): | |
arr = [6, 8, 3] | |
target = 14 | |
expected_output = 1 | |
self.assertEqual(count_sets(arr, target), expected_output) | |
def test_case_2(self): | |
arr = [5, 5, 15, 10] | |
target = 15 | |
expected_output = 3 | |
self.assertEqual(count_sets(arr, target), expected_output) | |
def test_case_big_array(self): | |
arr = range(21) | |
target = 31 | |
expected_output = 30 | |
self.assertNotEqual(count_sets(arr, target), expected_output) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment