Given a list, our task is to write a Python program to extract all K length sublists with lead to given summation.
Input : test_list = [6, 3, 12, 7, 4, 11], N = 21, K = 4
Output : [(6, 6, 6, 3), (6, 6, 3, 6), (6, 3, 6, 6), (6, 7, 4, 4), (6, 4, 7, 4), (6, 4, 4, 7), (3, 6, 6, 6), (3, 3, 3, 12), (3, 3, 12, 3), (3, 3, 4, 11), (3, 3, 11, 4), (3, 12, 3, 3), (3, 7, 7, 4), (3, 7, 4, 7), (3, 4, 3, 11), (3, 4, 7, 7), (3, 4, 11, 3), (3, 11, 3, 4), (3, 11, 4, 3), (12, 3, 3, 3), (7, 6, 4, 4), (7, 3, 7, 4), (7, 3, 4, 7), (7, 7, 3, 4), (7, 7, 4, 3), (7, 4, 6, 4), (7, 4, 3, 7), (7, 4, 7, 3), (7, 4, 4, 6), (4, 6, 7, 4), (4, 6, 4, 7), (4, 3, 3, 11), (4, 3, 7, 7), (4, 3, 11, 3), (4, 7, 6, 4), (4, 7, 3, 7), (4, 7, 7, 3), (4, 7, 4, 6), (4, 4, 6, 7), (4, 4, 7, 6), (4, 11, 3, 3), (11, 3, 3, 4), (11, 3, 4, 3), (11, 4, 3, 3)]
Explanation : All groups of length 4 and sum 21 are printed.
Input : test_list = [6, 3, 12, 7, 4, 11], N = 210, K = 4
Output : []
Explanation : Since no 4 size group sum equals 210, no group is printed as result.
In this all possible sublists of length K are computed using product(), sum() is used to compare the sublist’s sum with the required summation.
The original list is : [6, 3, 12, 7, 4, 11]
The sublists with of given size and sum : [(6, 6, 6, 3), (6, 6, 3, 6), (6, 3, 6, 6), (6, 7, 4, 4), (6, 4, 7, 4), (6, 4, 4, 7), (3, 6, 6, 6), (3, 3, 3, 12), (3, 3, 12, 3), (3, 3, 4, 11), (3, 3, 11, 4), (3, 12, 3, 3), (3, 7, 7, 4), (3, 7, 4, 7), (3, 4, 3, 11), (3, 4, 7, 7), (3, 4, 11, 3), (3, 11, 3, 4), (3, 11, 4, 3), (12, 3, 3, 3), (7, 6, 4, 4), (7, 3, 7, 4), (7, 3, 4, 7), (7, 7, 3, 4), (7, 7, 4, 3), (7, 4, 6, 4), (7, 4, 3, 7), (7, 4, 7, 3), (7, 4, 4, 6), (4, 6, 7, 4), (4, 6, 4, 7), (4, 3, 3, 11), (4, 3, 7, 7), (4, 3, 11, 3), (4, 7, 6, 4), (4, 7, 3, 7), (4, 7, 7, 3), (4, 7, 4, 6), (4, 4, 6, 7), (4, 4, 7, 6), (4, 11, 3, 3), (11, 3, 3, 4), (11, 3, 4, 3), (11, 4, 3, 3)]
Output
[[6, 6, 6, 3], [6, 6, 3, 6], [6, 3, 6, 6], [6, 7, 4, 4], [6, 4, 7, 4], [6, 4, 4, 7], [3, 6, 6, 6], [3, 3, 3, 12], [3, 3, 12, 3], [3, 3, 4, 11], [3, 3, 11, 4], [3, 12, 3, 3], [3, 7, 7, 4], [3, 7, 4, 7], [3, 4, 3, 11], [3, 4, 7, 7], [3, 4, 11, 3], [3, 11, 3, 4], [3, 11, 4, 3], [12, 3, 3, 3], [7, 6, 4, 4], [7, 3, 7, 4], [7, 3, 4, 7], [7, 7, 3, 4], [7, 7, 4, 3], [7, 4, 6, 4], [7, 4, 3, 7], [7, 4, 7, 3], [7, 4, 4, 6], [4, 6, 7, 4], [4, 6, 4, 7], [4, 3, 3, 11], [4, 3, 7, 7], [4, 3, 11, 3], [4, 7, 6, 4], [4, 7, 3, 7], [4, 7, 7, 3], [4, 7, 4, 6], [4, 4, 6, 7], [4, 4, 7, 6], [4, 11, 3, 3], [11, 3, 3, 4], [11, 3, 4, 3], [11, 4, 3, 3]]
Time Complexity: O(N^K), because we are generating all possible groups of length K with sum N, and each number in the list, can either be included or excluded in a group.
Space Complexity: O(K) because we are using the curr_group list to store the current group, and its length is at most K. Additionally, the recursion depth can go up to K, so the space complexity is O(K).