Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- This problem was asked by Google.
- Given a list of integers S and a target number k, write a function that returns a subset of S that adds up to k. If such a subset cannot be made, then return null.
- Integers can appear more than once in the list. You may assume all numbers in the list are positive.
- For example, given S = [12, 1, 61, 5, 9, 2] and k = 24, return [12, 9, 2, 1] since it sums up to 24.
- '''
- from itertools import combinations
- # Function 1 <----> Generate all the sublists of a list
- # If list = [1, 2, 3], there are 8 sublists:
- # [], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]
- def subLists(myList):
- N = len(myList)
- returnedList = list()
- returnedList.append([])
- for remaining in range(1, N):
- combinationsOfIndecesRemaining = list(combinations(list(range(N)), remaining))
- for comb in combinationsOfIndecesRemaining:
- sublist = list()
- for i in range(len(comb)):
- sublist.append(myList[comb[i]])
- returnedList.append(sublist)
- returnedList.append(myList)
- return returnedList
- def solve(myList, k):
- subs = subLists(myList)
- result = list()
- flag = False
- for sub in subs:
- if sum(sub) == k:
- flag = True
- result.append(sub)
- if flag == False:
- print("There is no sublist of list " + str(myList) + ", that its elements has sum = " + str(k))
- return None
- else:
- return result
- # MAIN FUNCTION
- myList1 = [12, 1, 61, 5, 9, 2]
- k1 = 24
- myList2 = [10, 15, 3, 4, 5, 20]
- k2 = 30
- print("The sublists of " + str(myList1) + " that have sum = " + str(k1) + " are: " + str(solve(myList1, k1)))
- print("The sublists of " + str(myList2) + " that have sum = " + str(k2) + " are: " + str(solve(myList2, k2)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement