Smallest number that cannot be formed from sum of numbers from array

There’s a beautiful algorithm for solving this problem in time O(n + Sort), where Sort is the amount of time required to sort the input array. The idea behind the algorithm is to sort the array and then ask the following question: what is the smallest positive integer you cannot make using the first k … Read more

Find all combinations of a list of numbers with a given sum

You could use itertools to iterate through every combination of every possible size, and filter out everything that doesn’t sum to 10: import itertools numbers = [1, 2, 3, 7, 7, 9, 10] target = 10 result = [seq for i in range(len(numbers), 0, -1) for seq in itertools.combinations(numbers, i) if sum(seq) == target] print(result) … Read more

Finding all possible combinations of numbers to reach a given sum

This problem can be solved with a recursive combinations of all possible sums filtering out those that reach the target. Here is the algorithm in Python: def subset_sum(numbers, target, partial=[]): s = sum(partial) # check if the partial sum is equals to target if s == target: print “sum(%s)=%s” % (partial, target) if s >= … Read more

tech