Advertisement
makispaiktis

DCP42- Sublists with specific sum

Oct 5th, 2020 (edited)
926
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. '''
  2. This problem was asked by Google.
  3. 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.
  4. Integers can appear more than once in the list. You may assume all numbers in the list are positive.
  5. For example, given S = [12, 1, 61, 5, 9, 2] and k = 24, return [12, 9, 2, 1] since it sums up to 24.
  6. '''
  7.  
  8. from itertools import combinations
  9.  
  10. # Function 1 <----> Generate all the sublists of a list
  11. # If list = [1, 2, 3], there are 8 sublists:
  12. # [], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]
  13.  
  14. def subLists(myList):
  15.     N = len(myList)
  16.     returnedList = list()
  17.     returnedList.append([])
  18.     for remaining in range(1, N):
  19.         combinationsOfIndecesRemaining = list(combinations(list(range(N)), remaining))
  20.         for comb in combinationsOfIndecesRemaining:
  21.             sublist = list()
  22.             for i in range(len(comb)):
  23.                 sublist.append(myList[comb[i]])
  24.             returnedList.append(sublist)
  25.     returnedList.append(myList)
  26.     return returnedList
  27.  
  28. def solve(myList, k):
  29.     subs = subLists(myList)
  30.     result = list()
  31.     flag = False
  32.     for sub in subs:
  33.         if sum(sub) == k:
  34.             flag = True
  35.             result.append(sub)
  36.     if flag == False:
  37.         print("There is no sublist of list " + str(myList) + ", that its elements has sum = " + str(k))
  38.         return None
  39.     else:
  40.         return result
  41.  
  42. # MAIN FUNCTION
  43. myList1 = [12, 1, 61, 5, 9, 2]
  44. k1 = 24
  45. myList2 = [10, 15, 3, 4, 5, 20]
  46. k2 = 30
  47. print("The sublists of " + str(myList1) + " that have sum = " + str(k1) + " are: " + str(solve(myList1, k1)))
  48. 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