codextj

target_sum_set_soln_2_py

Sep 10th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.94 KB | None | 0 0
  1. n,target,k = 6, 10, 1
  2. arr = [3,7, 1, 9, -1,5]
  3.  
  4. arr.sort()
  5.  
  6. # edge case with negative numbers therefore don't bisect
  7. # arr = arr[:bisect_right(arr, target)] #array will not contain any number greater than target
  8.  
  9. answ_cnt = 0
  10. def k_len_target_sum_subset(arr,target, subset_lst = []):
  11.     global answ_cnt
  12.     #print(subset_lst)
  13.     subset_sum = sum(subset_lst)
  14.     if target == subset_sum and len(subset_lst) == k:
  15.         answ_cnt+=1
  16.         print('ans',answ_cnt,subset_lst)
  17.         return
  18.        
  19.     if target < subset_sum or len(subset_lst) > k:
  20.         return False
  21.  
  22.     for idx,this_num in enumerate(arr):
  23.         k_len_target_sum_subset(arr[idx+1:], target, subset_lst+[this_num]) #magical thing happening here take your time to understand this
  24.        
  25. k_len_target_sum_subset(arr,target)
  26.  
  27. if answ_cnt ==0:
  28.     print('no solution')
  29.  
  30. '''
  31. k =1
  32. no solution
  33.  
  34. k = 2
  35. ans 1 [1, 9]
  36. ans 2 [3, 7]
  37.  
  38. k = 4
  39. ans 1 [-1, 1, 3, 7]
  40. '''
Add Comment
Please, Sign In to add comment