#! /bin/env python3 ''' The knapsack problem or the subset sum problem is known to be hard to solve. https://en.wikipedia.org/wiki/Knapsack_problem https://en.wikipedia.org/wiki/Subset_sum_problem Here we are given a list of positive integers and a single positive integer We want to determine if the there is a subset of the list of integers whose sum equals the given integer. The brute force method is to try all possibilities. That is, calculate the sums of all the subsets of the list of integers. For this, we use our new best friend: power set. ''' from itertools import chain, combinations ## for hw1 you are not allowed to use itertools def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) def subsetsums(list): ps = powerset(list) sums = [sum(n) for n in ps] return sums def allindices(lst, element): i = 0 result = [] if element in lst: i = lst.index(element) result.append(i) while element in lst[i+1:]: i = lst.index(element,i+1) result.append(i) return result return False def lcallindices(lst,element): return [i for (i,item) in enumerate(lst) if item == element] l = [1,3,5,7,9,11,13] ps = powerset(l) r = subsetsums(l) ai = allindices(r,21) lcai = lcallindices(r,21)